[erlang-questions] if and fun with erl

Bengt Kleberg bengt.kleberg@REDACTED
Tue Feb 1 14:27:55 CET 2011


Greetings,

The problem is due to a "," too many. Try:

Compare = fun(X, Y) ->
        if X>Y -> greater;
          X==Y -> equal;
          X<Y -> less
        end
      end.


Also, consider using =:=, to get into the habit.


bengt

On Tue, 2011-02-01 at 14:20 +0100, Yann SECQ wrote:
> 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.
> 



More information about the erlang-questions mailing list