[erlang-questions] How do funs work ?
Wed Mar 28 20:08:31 CEST 2012
On Wednesday, March 28, 2012, Yoshihiro Tanaka wrote:
> Yes, you are right. But my point is, in this fun, each part of 'fun()
> -> something end()' will be executed during F2 is created ?
> or that part will be executed when I call F2 like F2() ? I'm not sure
> how it works.
If I recall correctly, a new function is not created, just the bindings. For instance, if you take a fun and send it in a message, the whole fun isn't being sent, just a reference to the function in the module and the variable bindings. For example:
example(X, Y, Z, P) ->
F = fun(W) -> (X + Y * Z) / W end,
P ! F.
When example(1, 2, 3, Pid) is called, a new fun is not created (F(W) -> (1 + 2 * 3) / W end) and sent to Pid. Instead, what's sent to Pid is a reference to the function definition in module for_example with the bindings X = 1, Y = 2, Z = 3.
If Pid is on another node with a different version of the for_example module, then it will fail. Not sure exactly what will happen, whether the node will crash, the process crash, or just the message get discarded, but you could probably experiment to figure it out.
Someone correct me if I am wrong. This is partly based on memory and partly based on how I figure it would be implemented.
More information about the erlang-questions