[erlang-questions] if and fun with erl

Taylor Venable taylor@REDACTED
Tue Feb 1 14:37:23 CET 2011


On Tue, Feb 1, 2011 at 08:20, Yann SECQ <yann.secq@REDACTED> wrote:
> 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'

Think of ";" and "," as statement *separators* not statement
*terminators* like in C/C++/Java. Since the only statement directly
inside your fun is the if, there's no need to put a "," after it.

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

> 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 works because now you've got two expressions inside your fun, so
you need the "," after the variable assignment to separate the
assignment (which contains the if in the RHS) from the "Res".

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

This is because when defining a function inside a module, not using an
explicit fun expression, you don't need to provide an "end" for the
function itself; it ends at the full stop (period). So in this case,
you only need one "end" for the if expression.

Hope this explanation helps.

-- 
Taylor C. Venable
http://metasyntax.net/


More information about the erlang-questions mailing list