tags:

views:

322

answers:

3

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),
%% ...
+11  A: 

There is no way to do exactly that. The way it's usually done is to 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),
%% ...
legoscia
+5  A: 

If you feel like twisting things a little bit:

Y = fun(M,B) -> G = fun(F) -> M(fun() -> (F(F))() end, B) end, G(G) end.
spawn(Y(fun(F, ParentPid) -> fun() -> ParentPid ! wake_up, receive after 1000 -> ok end, F() end end, self())).

Flush the messages couple times to see the result:

flush().

Of course, Y is more useful if you put it in some sort of library. Also you can find this post on Y Combinators: http://bc.tech.coop/blog/070611.html quite interesting

zakovyrya
+1  A: 

The Erlang language does not expose any way for anonymous functions to refer to them self, but there is a rumour that Core Erlang (an intermediate but official representation in the compiler phases) does have such a feature.

I don't know why I am forwarding this, but you know, if you happen to be generating Core Erlang in a DSL or similar it is something that is within reach.

Christian