遞迴和接收
遞迴可用於接收多條訊息
defmodule Processes do
def receiver do
receive do
{:ok, val} ->
IO.puts "Received Value: #{val}"
_ ->
IO.puts "Received something else"
end
receiver
end
end
iex(1)> pid = spawn Processes, :receiver, []
#PID<0.95.0>
iex(2)> send pid, {:ok, 10}
Received Value: 10
{:ok, 10}
iex(3)> send pid, {:ok, 42}
{:ok, 42}
Received Value: 42
iex(4)> send pid, :random
:random
Received something else
Elixir 將使用尾呼叫遞迴優化,只要函式呼叫是函式中發生的最後一件事,就像在示例中一樣。