In Erlang http://en.wikipedia.org/wiki/Erlang_(programming_language)有没有办法引用当前正在执行的函数)?
这对于产生无限循环很有用:
spawn(fun() -> do_something, this_fun() end)
在 JavaScript 中arguments.callee
就是这样做的,请参阅规范MDC https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/callee.
编辑回答“你为什么要这样做”:主要是出于好奇;在原型设计时定义一个计时器也很有用:
Self = self(),
spawn(fun() -> Self ! wake_up, receive after 1000 -> nil end, this_fun() end),
%% ...
在 Erlang/OTP 17.0 及更高版本中,您可以为此使用命名的 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),
%% ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)