if and fun with erl

Yann SECQ yann.secq@REDACTED
Tue Feb 1 14:20:44 CET 2011


Dear erlang users,

I'm beginnning my journey with this language and I'm a bit
surprised by a strange behaviour concerning if within fun.
I'm probably missing something obvious but I've not been
able to find any clue on the official documentation or the web.

I wanted to write within the erlang shell something like:

13> Compare = fun(X, Y) ->
       if X>Y -> greater;
          X==Y -> equal;
          X<Y -> less
       end.
* 1: syntax error before: '.'

So I tried to add another 'end' to match the 'if' declaration

13> Compare = fun(X, Y) ->
       if X>Y -> greater;
          X==Y -> equal;
          X<Y -> less
       end,
     end.
* 1: syntax error before: 'end'

With no more success. What surprises me is that if I catch
the conditional return value it works:

14> Compare = fun(X, Y) ->
       Res = if X>Y -> greater;
                X==Y -> equal;
                X<Y -> less
             end,
       Res
       end.
#Fun<erl_eval.12.113037538>

What bugs me is that when doing this in a module:

compare(X, Y) ->
   if X>Y -> greater;
      X==Y -> equal;
      true -> less
end.

It works as expected !

Can someone explain me what I'm missing to be able to return
directly the conditional result without having to go through
the Res temporary variable when using erl ?

Thank you for your help, yann.

-- 
Yann.Secq{at}univ-lille1.fr | http://www.lifl.fr/~secq
Universite de Lille 1       | http://www.univ-lille1.fr
Ouverture & Independance    | http://www.ouverture-independance.fr
Appel des Appels            | http://lille.appeldesappels.fr

"Ne désespérez jamais. Faites infuser davantage.", Henri Michaux


More information about the erlang-questions mailing list