[erlang-questions] A tad confused about function parameters

Joe Armstrong erlang@REDACTED
Mon Mar 16 20:38:23 CET 2009


Whenever you say F = fun() -> .... end.

You create a closure (think of F as a pointer to a function, where the
body of the function has not yet been evaluated).

When you say F() you force evaluation of the function. spawn(F)
creates a new process
and then evaluates F() *within* the new process.

 so spawn(fun() -> ... self()  .... end). means spawn a new process
*then* evaluate
... self() ... *inside* the new process - thus self() is the Pid of
the new process.

S = self(),
spawn(fun() -> ... S ... end) is different since S in evaluated in the
parent process, then
just passed as a variable into the closure.

/Joe






On Wed, Mar 11, 2009 at 11:31 PM, Allen McPherson <mcpherson@REDACTED> wrote:
> Here's a snippet of code that I'm using:
>
> %%  Once nodes have been started we launch the code to execute the
> %%  benchmarks.
> launch(L) ->
>     launch(L, []).
> launch([], Pids) ->
>     Pids;
> launch([H|T], Pids) ->
>     S = self(),             %  loop(self(), start) would evaluate
> self() inside loop() function
>     launch(T, lists:append(Pids, [spawn(H, fun() -> loop(S, start)
> end)])).
>
> %%  Main benchmark loop.  Receives request for particular type of test.
> %%  Spawns code to handle benchmark on its local node.
> loop(MasterPid, Mode) ->
>     ...
>
>
> 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, but it's getting evaluated after the spawn
> on node
> 'H'.
>
> Probably another dumb question, but can someone shed some light this.
> It seems like a fundamental concept to understand.
>
> --
> Al
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list