[erlang-questions] How do funs work ?
Thu Mar 29 11:00:55 CEST 2012
Just as a reference, some time ago Kresten wrote a really interested
article about funs and transferring funs between Erlang nodes. Might
be of interest:
On Thu, Mar 29, 2012 at 9:53 AM, Yoshihiro Tanaka <hirotnkg@REDACTED> wrote:
> Thank you David for making it clear.
> It all makes sense.
> On Wed, Mar 28, 2012 at 11:08 AM, David Mercer <dmercer@REDACTED> wrote:
>> 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.
> erlang-questions mailing list
More information about the erlang-questions