[erlang-questions] if and fun with erl

Frédéric Trottier-Hébert <>
Tue Feb 1 14:29:01 CET 2011


On 2011-02-01, at 08:20 AM, 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: '.'

This is missing an 'end'. the syntax is 'fun([Args]) -> ... end' (where the [] around Args mean they're optional) and 'if ... end'.
> 
> 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'
> 
The ',' is an expression, not a line terminator; you do not need it in this case.

> 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>

This is because now you add a ',' and the Res variable, which are two separate expressions. 'Res' must not be followed by a comma (and isn't) because no expression comes after. This is normal and expected behaviour.
> 
> 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 !

Of course. The syntax is fine this time!

> 
> 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 ?

if Cond1 -> Ret1;
   Cond2 -> Ret2;
   ...
   CondN -> RetN
end.

You might want to give a read to one of my blog posts, 'On Erlang's Syntax' (http://ferd.ca/on-erlang-s-syntax.html) which attempts to make this kind of syntactic issues easier to understand. Hopefully this will help.


--
Fred Hébert
http://www.erlang-solutions.com





More information about the erlang-questions mailing list