[erlang-questions] A tad confused about function parameters
Hynek Vychodil
vychodil.hynek@REDACTED
Thu Mar 12 00:31:18 CET 2009
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)])).
You can read fun() -> loop(self(), start) end as make function which do
loop(self(), start) and evaluate it in new process. It means self() is
evaluated in this process not in master process. It not means that self() is
evaluated in loop/2 but outside it even inside it's process which cause
trouble.
You can rewrite it using list comprehension
launch(L)->
S=self(),
[ spawn(N, fun()->loop(S, start) end) || N<-L ].
or in tail call manner (lists:append/2 or ++ is not often used especially in
loop where first parameter is growing)
launch(L) -> launch(L, []).
launch([], Pids)->lists:reverse(Pids); % or just Pids if doesn't care Pids
order
launch([H|T], Pids)->
S=self(),
launch(T, [pawn(N, fun()->loop(S, start) end)|Pids]).
It's common idiom in Erlang ot avoid lists:append/2 misuse.
>
> 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
>
--
--Hynek (Pichi) Vychodil
Analyze your data in minutes. Share your insights instantly. Thrill your
boss. Be a data hero!
Try Good Data now for free: www.gooddata.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090312/a2445a1b/attachment.htm>
More information about the erlang-questions
mailing list