如何生成带参数的匿名函数?
How to spawn an anonymous function with arguments?
在 elixir 中,我们有 spawn/1
生成不带任何参数的匿名函数,spawn/3
生成带参数的完全限定函数。但是如何生成需要参数的匿名函数?
示例:我想 运行 一个匿名函数,该函数在满足特定条件之前接收消息。参数是能够执行递归步骤的函数本身。
loop = fn f ->
receive do
{:end, pid} -> send(pid, "exiting")
{_, pid} ->
send(pid, "unrecognized message, keep waiting...")
f.(f)
end
end
child = spawn() # How do I spawn it passing itself as an argument?
您可以创建一个新的匿名函数来处理对 loop
的第一次调用,让 loop
处理其余的:
spawn(fn -> loop.(loop) end)
iex(1)> loop = fn f ->
...(1)> receive do
...(1)> {:end, pid} -> send(pid, "exiting")
...(1)> {_, pid} ->
...(1)> send(pid, "unrecognized message, keep waiting...")
...(1)> f.(f)
...(1)> end
...(1)> end
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(2)> pid = spawn(fn -> loop.(loop) end)
#PID<0.90.0>
iex(3)> send pid, {:foo, self}
{:foo, #PID<0.80.0>}
iex(4)> flush
"unrecognized message, keep waiting..."
:ok
iex(5)> send pid, {:end, self}
{:end, #PID<0.80.0>}
iex(6)> flush
"exiting"
:ok
iex(7)> Process.alive? pid
false
在 elixir 中,我们有 spawn/1
生成不带任何参数的匿名函数,spawn/3
生成带参数的完全限定函数。但是如何生成需要参数的匿名函数?
示例:我想 运行 一个匿名函数,该函数在满足特定条件之前接收消息。参数是能够执行递归步骤的函数本身。
loop = fn f ->
receive do
{:end, pid} -> send(pid, "exiting")
{_, pid} ->
send(pid, "unrecognized message, keep waiting...")
f.(f)
end
end
child = spawn() # How do I spawn it passing itself as an argument?
您可以创建一个新的匿名函数来处理对 loop
的第一次调用,让 loop
处理其余的:
spawn(fn -> loop.(loop) end)
iex(1)> loop = fn f ->
...(1)> receive do
...(1)> {:end, pid} -> send(pid, "exiting")
...(1)> {_, pid} ->
...(1)> send(pid, "unrecognized message, keep waiting...")
...(1)> f.(f)
...(1)> end
...(1)> end
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(2)> pid = spawn(fn -> loop.(loop) end)
#PID<0.90.0>
iex(3)> send pid, {:foo, self}
{:foo, #PID<0.80.0>}
iex(4)> flush
"unrecognized message, keep waiting..."
:ok
iex(5)> send pid, {:end, self}
{:end, #PID<0.80.0>}
iex(6)> flush
"exiting"
:ok
iex(7)> Process.alive? pid
false