Erlang:如何从身体内引用匿名函数? [英] Erlang: how can I reference an anonymous function from within the body?

查看:108
本文介绍了Erlang:如何从身体内引用匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Erlang 有没有参考当前执行的功能)? p>

这将有助于产生无限循环:

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

在JavaScript 参数.callee 只是这样,请参阅的规范MDC



编辑回答为什么要这样做:大多是好奇心;在定型时定义一个计时器也很有用:

  Self = self(),
spawn - > Self!wake_up,接收后1000 - > nil end,this_fun()end),
%% ...


解决方案

在Erlang / OTP 17.0-rc1中,您可以使用命名乐趣:

  1> Self = self(),
1> Fun = fun ThisFun() - >
自我! wake_up,
接收1000 - > nil end,
ThisFun()
end。
#Fun< erl_eval.44.71889879>
2>产卵(FUN)。
< 0.35.0>
3>齐平()。
Shell得到wake_up
Shell已经有了wake_up
Shell已经有了wake_up
ok






在早期版本中,没有办法做到这一点。您可以将函数本身作为参数传递:

  Self = self(),
Fun = fun(ThisFun) - >
自我! wake_up,
接收1000 - > nil end,
ThisFun(ThisFun)
end
spawn(fun() - > Fun(Fun)end),
%% ...


In Erlang is there a way reference the currently executing function)?

That would be useful to spawn an infinite loop:

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

In JavaScript arguments.callee does just that, see the specification on MDC.

Edit to answer a 'why would you do that': mostly curiosity; it is also useful to define a timer when prorotyping:

Self = self(),
spawn(fun() -> Self ! wake_up, receive after 1000 -> nil end, this_fun() end),
%% ...

解决方案

In Erlang/OTP 17.0-rc1, you can use a named fun for that:

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


In earlier versions, there is no way to do exactly that. You could pass the function itself as an argument:

Self = self(),
Fun = fun(ThisFun) ->
          Self ! wake_up,
          receive after 1000 -> nil end,
          ThisFun(ThisFun)
      end
spawn(fun() -> Fun(Fun) end),
%% ...

这篇关于Erlang:如何从身体内引用匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆