[erlang-questions] How do funs work ?

Yoshihiro Tanaka hirotnkg@REDACTED
Wed Mar 28 10:51:56 CEST 2012


Hello,

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
       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()
             end()
           end()
         end()
       end()
     end.


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
Yoshihiro



More information about the erlang-questions mailing list