[erlang-questions] How do funs work ?
黃耀賢 (Yau-Hsien Huang)
Thu Mar 29 16:18:12 CEST 2012
On Wed, Mar 28, 2012 at 4:51 PM, Yoshihiro Tanaka <>wrote:
> I have a function which returns fun as below:
> make_fun(_, , F) -> F;
> make_fun(Operator, [Operand1, Operand2|Operands], F) ->
> F2 = case Operator of
> plus -> fun() -> Operand1 + Operand2 + F() end;
> minus -> fun() -> Operand1 - Operand2 + F() end
> make_fun(Operator, Operands, F2).
> When I call it as:
> F1 = make_fun(plus, lists:seq(1,10), fun() -> 0 end).
> Is F1 same as F2 below ?
> F2 = fun() -> 1 + 2 +
> fun() -> 3 + 4 +
> fun() -> 5 + 6 +
> fun() -> 7 + 8 +
> fun() -> 9 + 10 +
> fun() -> 0 end()
No, F1 is not the same as F2. A function F is a function definition, then
F() is a function application. The F1 shell be expand as
9 + 10 +
7 + 8 +
5 + 6 +
3 + 4 +
1 + 2 + (fun() -> 0 end)()
All F() evaluates itself, but F doesn't. Functions applied can be reduced,
and F1 is reduced as a form
9 + 10 +
(7 + 8 +
(5 + 6 +
(3 + 4 +
(1 + 2 + 0)
) ) )
Note that it cannot be a function with any binary operator + accompanied
by a function definition. For example, try to write a program with you
make_fun/3 definition, and make the F1 function in Erlang shell. And
give following instructions:
F3 = fun()-> 1 + 2 + F1 end, F3().
You will get a bad argument error in arithmetic expression. Obviously
in your make_fun/3, every time it make a fun() -> end expression,
it evaluates a preceding function and puts the result as an operand of +,
and the preceding function is not a function definition any more.
> Also, is there any difference between funs that are defined at runtime
> and funs that are defined at compile time in terms of how they are
> executed ?
> Thank you
> erlang-questions mailing list
--- Y-H. H.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the erlang-questions