[erlang-questions] A tad confused about function parameters

Richard Carlsson richardc@REDACTED
Thu Mar 12 07:59:39 CET 2009


Allen McPherson wrote:
> The line in question is:
>             S = self(),
> ----->     launch(T, lists:append(Pids, [spawn(H, fun() -> loop(S,
> start) end)])).
> 
> I find that if I use:
>             launch(T, lists:append(Pids, [spawn(H, fun() ->
> loop(self(), start) end)])).
> 
> instead, self() is evaluated everywhere in loop() that MasterPid occurs.
> Intuitively I sort of get it, by formally I don't really understand
> what's going on here...why the delayed evaluation? I would think it  
> would be evaluate before the spawn

Well, the whole point of a lambda expression is to delay the evaluation
of everything between fun...end. The call to self() is just another
subexpression, so if you expect that to be evaluated immediately, then
surely you'd also expect the call to loop(...) to run right after that?
Of course not - that was why you used a fun to begin with.

The trap is that it's easy to start thinking about self() (and some
other builtins like node()) as "more primitive" - mere symbols - and
expect them to work like variables. But they are just function calls.

     /Richard




More information about the erlang-questions mailing list