[erlang-questions] if and fun with erl

Fernando Benavides <>
Tue Feb 1 14:28:30 CET 2011


If statements require a true clause. On your module you have one, on the
console you don't.

Try with:
13> Compare = fun(X, Y) ->
>        if X>Y -> greater;
>           X==Y -> equal;
>           true -> less
>        end
> end.

Cheers!

                                                                        
________________________________________________________________________

                                                      Fernando Benavides

                                              
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