[erlang-questions] Newbie question about Erlang style

Richard Carlsson <>
Wed Feb 27 23:36:54 CET 2008


Convey Christian J NPRI wrote:
> Is there any non-aesthetic reason prefer one of the following  
> approaches over the other?
>
>
> if Foo  -> X = 1;
>   true -> X = 2
> end
>
> vs.
>
> X = if
>       Foo  -> 1;
>       true -> 2
>     end

Not really. The main deciding factors are personal taste, number of
clauses, and similarity of guard expressions. (I.e., you might want to
line them up if there are several similar clauses.)

Kevin Scaldeferri wrote:
> A related question: are all variables function scoped in Erlang?   
> Obviously, the first example wouldn't work at all if the branches of  
> an if or case created a new scope.  Is there any way to explicitly  
> create a new scope?

Only by using a fun-expression. Variables introduced in the head of
a fun are local to that fun (or to that fun-clause, if it's a multi-
clause fun).

But my advice is to avoid doing tricks with funs for local scope.
Your code will be more readable if you lift such things out to separate
functions with decent names. Erlang is not Haskell, and let-bindings
don't really fit in with the normal variable binding rules.

That said, you can find a LET-macro definition in eunit.hrl
(http://svn.process-one.net/contribs/trunk/eunit/include/eunit.hrl),
for those cases where you really need it. I repeat, though: avoid this
sort of thing in normal code.

     /Richard



More information about the erlang-questions mailing list