gpt4 book ai didi

Erlang:如何从体内引用匿名函数?

转载 作者:行者123 更新时间:2023-12-03 22:53:01 26 4
gpt4 key购买 nike

Erlang有没有办法引用当前正在执行的函数)?

这对于产生无限循环很有用:

spawn(fun() -> do_something, this_fun() end)

在 JavaScript arguments.callee这样做,请参阅 MDC 上的规范.

编辑回答“你为什么要这样做”:主要是好奇心;在原型(prototype)设计时定义计时器也很有用:
Self = self(),
spawn(fun() -> Self ! wake_up, receive after 1000 -> nil end, this_fun() end),
%% ...

最佳答案

在 Erlang/OTP 17.0-rc1 中,您可以为此使用命名的 fun:

1> Self = self(),
1> Fun = fun ThisFun() ->
Self ! wake_up,
receive after 1000 -> nil end,
ThisFun()
end.
#Fun<erl_eval.44.71889879>
2> spawn(Fun).
<0.35.0>
3> flush().
Shell got wake_up
Shell got wake_up
Shell got wake_up
ok

在早期版本中,没有办法做到这一点。您可以将函数本身作为参数传递:
Self = self(),
Fun = fun(ThisFun) ->
Self ! wake_up,
receive after 1000 -> nil end,
ThisFun(ThisFun)
end
spawn(fun() -> Fun(Fun) end),
%% ...

关于Erlang:如何从体内引用匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1179655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com