Skip to content

Latest commit

 

History

History
183 lines (140 loc) · 5.26 KB

process_mailbox.livemd

File metadata and controls

183 lines (140 loc) · 5.26 KB

Process Mailbox

Mix.install([
  {:jason, "~> 1.4"},
  {:kino, "~> 0.9", override: true},
  {:youtube, github: "brooklinjazz/youtube"},
  {:hidden_cell, github: "brooklinjazz/hidden_cell"}
])

Navigation

Process Mailbox

Using spawn/1, send/2, and receive You're going to create a Mailbox process which recursively sends and receives messages.

Spawn The Mailbox

The Mailbox should recursively loop and wait to receive a message.

maibox_process = spawn(fn -> Mailbox.loop() end)

Send Mail

Send the mailbox process a {:send, message} message and it should store the message.

send(mailbox_process, {:send, "You've got mail!"})

Read Mail

Send the mailbox process a {:read, from_pid} message and it should send the most recent message back to the sender and remove it from the mailbox.

send(mailbox_process, {:read, self()})

receive do
  message -> message 
end
# Returns "You've Got Mail!"

If there are no messages, send an :empty message back.

send(mailbox_process, {:read, self()})

receive do
  message -> message 
end
# Returns :empty
Example Solution
defmodule Mailbox do
  def loop(state \\ []) do
    receive do
      {:send, message} ->
        IO.inspect(message)
        loop([message | state])

      {:read, from_pid} ->
        case state do
          [head | tail] ->
            send(from_pid, head)
            loop(tail)

          [] ->
            send(from_pid, :empty)
            loop([])
        end
    end
  end
end
defmodule Mailbox do
  @moduledoc """
  Documentation for `Mailbox`
  """

  @doc """
  Recursively loop and receive messages.
  This doctest will timeout if there is no implementation.

  ## Examples

      iex> mailbox_process = spawn(fn -> Mailbox.loop() end)
      iex> send(mailbox_process, {:send, "Hello!"})
      iex> send(mailbox_process, {:read, self()})
      iex> receive do
      ...>  message -> message 
      ...> end
      "Hello!"
  """
  def loop(state \\ []) do
  end
end

Commit Your Progress

DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.

Run git status to ensure there are no undesirable changes. Then run the following in your command line from the curriculum folder to commit your progress.

$ git add .
$ git commit -m "finish Process Mailbox exercise"
$ git push

We're proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.

We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.

Navigation