take-a-number

This commit is contained in:
Danil Negrienko 2023-12-18 21:00:48 -05:00
parent 7332230435
commit 53d94ff371
11 changed files with 420 additions and 0 deletions

View File

@ -0,0 +1,21 @@
{
"authors": [
"angelikatyborska"
],
"contributors": [
"neenjaw"
],
"files": {
"solution": [
"lib/take_a_number.ex"
],
"test": [
"test/take_a_number_test.exs"
],
"exemplar": [
".meta/exemplar.ex"
]
},
"language_versions": ">=1.10",
"blurb": "Learn about processes and process identifiers by writing an embedded system for a Take-A-Number machine."
}

View File

@ -0,0 +1 @@
{"track":"elixir","exercise":"take-a-number","id":"7972e7b5dd264e70942940e6e3fd02d6","url":"https://exercism.org/tracks/elixir/exercises/take-a-number","handle":"negrienko","is_requester":true,"auto_approve":false}

View File

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

24
elixir/take-a-number/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where third-party dependencies like ExDoc output generated docs.
/doc/
# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
nil-*.tar

View File

@ -0,0 +1,75 @@
# Help
## Running the tests
From the terminal, change to the base directory of the exercise then execute the tests with:
```bash
$ mix test
```
This will execute the test file found in the `test` subfolder -- a file ending in `_test.exs`
Documentation:
* [`mix test` - Elixir's test execution tool](https://hexdocs.pm/mix/Mix.Tasks.Test.html)
* [`ExUnit` - Elixir's unit test library](https://hexdocs.pm/ex_unit/ExUnit.html)
## Pending tests
In test suites of practice exercises, all but the first test have been tagged to be skipped.
Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol.
For example:
```elixir
# @tag :pending
test "shouting" do
assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```
If you wish to run all tests at once, you can include all skipped test by using the `--include` flag on the `mix test` command:
```bash
$ mix test --include pending
```
Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the file `test/test_helper.exs`.
```elixir
# ExUnit.configure(exclude: :pending, trace: true)
```
## Useful `mix test` options
* `test/<FILE>.exs:LINENUM` - runs only a single test, the test from `<FILE>.exs` whose definition is on line `LINENUM`
* `--failed` - runs only tests that failed the last time they ran
* `--max-failures` - the suite stops evaluating tests when this number of test failures
is reached
* `--seed 0` - disables randomization so the tests in a single file will always be ran
in the same order they were defined in
## Submitting your solution
You can submit your solution using the `exercism submit lib/take_a_number.ex` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Elixir track's documentation](https://exercism.org/docs/tracks/elixir)
- The [Elixir track's programming category on the forum](https://forum.exercism.org/c/programming/elixir)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
If you're stuck on something, it may help to look at some of the [available resources](https://exercism.org/docs/tracks/elixir/resources) out there where answers might be found.

View File

@ -0,0 +1,40 @@
# Hints
## General
- Read about processes in the official [Getting Started guide][getting-started-processes].
- Read [this blog post][mullen-processes] about Elixir processes.
## 1. Start the machine
- The machine should run in a new process. There is [a built-in function that starts a new process][kernel-spawn-1].
- You will need another function that the new process will execute.
## 2. Report the machine state
- The machine's process needs to respond to messages.
- There is [a built-in function that waits for a message to arrive in the process's mailbox][kernel-receive].
- There is [a built-in function that sends a message to another process][kernel-send].
- Use recursion to wait for more than one message.
- Pass the machine's state as an argument to the recursive function.
## 3. Give out numbers
- This step is conceptually the same as the previous step. The only difference is the need to update the machine's state.
## 4. Stop the machine
- This step doesn't require sending any messages as a response.
- A process will exit if it has no more code to execute.
- This is a base case of the recursive function.
## 5. Ignore unexpected messages
- This step doesn't require sending any messages as a response.
- You can use `_` to match all messages that didn't match previous patterns.
[getting-started-processes]: https://elixir-lang.org/getting-started/processes.html
[mullen-processes]: https://samuelmullen.com/articles/elixir-processes-send-and-receive
[kernel-spawn-1]: https://hexdocs.pm/elixir/Kernel.html#spawn/1
[kernel-receive]: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#receive/1
[kernel-send]: https://hexdocs.pm/elixir/Kernel.html#send/2

View File

@ -0,0 +1,114 @@
# Take-A-Number
Welcome to Take-A-Number on Exercism's Elixir Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
## Processes
In Elixir, all code runs inside processes.
By default, a function will execute in the same process from which it was called. When you need to explicitly run a certain function in a new process, use `spawn/1`:
```elixir
spawn(fn -> 2 + 2 end)
# => #PID<0.125.0>
```
`spawn/1` creates a new process that executes the given function and returns a _process identifier_ (PID). The new process will stay alive as long as the function executes, and then silently exit.
Elixir's processes should not be confused with operating system processes. Elixir's processes use much less memory and CPU. It's perfectly fine to have Elixir applications that run hundreds of Elixir processes.
### Messages
Processes do not directly share information with one another. Processes _send and receive messages_ to share data.
You can send a message to any process with `send/2`. The first argument to `send/2` is the PID of the recipient, the second argument is the message.
A message can be of any type. Often it consists of atoms and tuples. If you want to get a response, you should include the PID of the sender somewhere in the message. You can get the PID of the current process with `self()`.
`send/2` does not check if the message was received by the recipient, nor if the recipient is still alive. The message ends up in the recipient's _mailbox_ and it will only be read if and when the recipient explicitly asks to _receive messages_.
A message can be read from a mailbox using the `receive/1` macro. It accepts a `do` block that can [pattern match][exercism-pattern-matching] on the messages.
```elixir
receive do
{:ping, sender_pid} -> send(sender_pid, :pong)
:do_nothing -> nil
end
```
`receive/1` will take _one message_ from the mailbox that matches any of the given patterns and execute the expression given for that pattern. If there are no messages in the mailbox, or none of messages in the mailbox match any of the patterns, `receive/1` is going to wait for one.
### Receive loop
If you want to receive more than one message, you need to call `receive/1` recursively. It is a common pattern to implement a recursive function, for example named `loop`, that calls `receive/1`, does something with the message, and then calls itself to wait for more messages. If you need to carry some state from one `receive/1` call to another, you can do it by passing an argument to that `loop` function.
## PIDs
Process identifiers are their own data type. They function as _mailbox addresses_ - if you have a process's PID, you can send a message to that process. PIDs are usually created indirectly, as a return value of functions that create new processes, like `spawn`.
[exercism-pattern-matching]: https://exercism.org/tracks/elixir/concepts/pattern-matching
## Instructions
You are writing an embedded system for a Take-A-Number machine. It is a very simple model. It can give out consecutive numbers and report what was the last number given out.
## 1. Start the machine
Implement the `start/0` function. It should spawn a new process that has an initial state of `0` and is ready to receive messages. It should return the process's PID.
```elixir
TakeANumber.start()
# => #PID<0.138.0>
```
Note that each time you run this code, the PID may be different.
## 2. Report the machine state
Modify the machine so that it can receive `{:report_state, sender_pid}` messages. It should send its current state (the last given out ticket number) to `sender_pid` and then wait for more messages.
```elixir
machine_pid = TakeANumber.start()
send(machine_pid, {:report_state, self()})
receive do
msg -> msg
end
# => 0
```
## 3. Give out numbers
Modify the machine so that it can receive `{:take_a_number, sender_pid}` messages. It should increase its state by 1, send the new state to `sender_pid`, and then wait for more messages.
```elixir
machine_pid = TakeANumber.start()
send(machine_pid, {:take_a_number, self()})
receive do
msg -> msg
end
# => 1
```
## 4. Stop the machine
Modify the machine so that it can receive a `:stop` message. It should stop waiting for more messages.
## 5. Ignore unexpected messages
Modify the machine so that when it receives an unexpected message, it ignores it and continues waiting for more messages.
## Source
### Created by
- @angelikatyborska
### Contributed to by
- @neenjaw

View File

@ -0,0 +1,15 @@
defmodule TakeANumber do
def start() do
spawn(fn -> loop(0) end)
end
defp loop(number) do
new_state = receive do
:stop -> exit(:ok)
{:report_state, pid} -> send(pid, number)
{:take_a_number, pid} -> send(pid, number + 1)
_ -> number
end
loop(new_state)
end
end

View File

@ -0,0 +1,28 @@
defmodule TakeANumber.MixProject do
use Mix.Project
def project do
[
app: :take_a_number,
version: "0.1.0",
# elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end

View File

@ -0,0 +1,96 @@
defmodule TakeANumberTest do
use ExUnit.Case
@tag task_id: 1
test "starts a new process" do
pid = TakeANumber.start()
assert is_pid(pid)
assert pid != self()
assert pid != TakeANumber.start()
end
@tag task_id: 2
test "reports its own state" do
pid = TakeANumber.start()
send(pid, {:report_state, self()})
assert_receive 0
end
@tag task_id: 2
test "does not shut down after reporting its own state" do
pid = TakeANumber.start()
send(pid, {:report_state, self()})
assert_receive 0
send(pid, {:report_state, self()})
assert_receive 0
end
@tag task_id: 3
test "gives out a number" do
pid = TakeANumber.start()
send(pid, {:take_a_number, self()})
assert_receive 1
end
@tag task_id: 3
test "gives out many consecutive numbers" do
pid = TakeANumber.start()
send(pid, {:take_a_number, self()})
assert_receive 1
send(pid, {:take_a_number, self()})
assert_receive 2
send(pid, {:take_a_number, self()})
assert_receive 3
send(pid, {:report_state, self()})
assert_receive 3
send(pid, {:take_a_number, self()})
assert_receive 4
send(pid, {:take_a_number, self()})
assert_receive 5
send(pid, {:report_state, self()})
assert_receive 5
end
@tag task_id: 4
test "stops" do
pid = TakeANumber.start()
assert Process.alive?(pid)
send(pid, {:report_state, self()})
assert_receive 0
send(pid, :stop)
send(pid, {:report_state, self()})
refute_receive 0
refute Process.alive?(pid)
end
@tag task_id: 5
test "ignores unexpected messages and keeps working" do
pid = TakeANumber.start()
send(pid, :hello?)
send(pid, "I want to speak with the manager")
send(pid, {:take_a_number, self()})
assert_receive 1
send(pid, {:report_state, self()})
assert_receive 1
# This is necessary because `Process.info/1` is not guaranteed to return up-to-date info immediately.
dirty_hacky_delay_to_ensure_up_to_date_process_info = 200
:timer.sleep(dirty_hacky_delay_to_ensure_up_to_date_process_info)
# Do not use `Process.info/1` in your own code.
# It's meant for debugging purposes only.
# We use it here for didactic purposes because there is no alternative that would achieve the same result.
assert Keyword.get(Process.info(pid), :message_queue_len) == 0
end
end

View File

@ -0,0 +1,2 @@
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true, seed: 0)