[erlang-questions] Erlang elseif

Thomas Lindgren thomasl_erlang@REDACTED
Fri Nov 21 10:05:21 CET 2008




--- On Fri, 11/21/08, Daniel Rönnqvist <kdronnqvist@REDACTED> wrote:
> I am merely trying to figure out why this simple logical
> control structure
> don't exist;
> 
> If <expression> == true then <expression>
> elseif <expression> then <expression>
> else <expression>

The clause to use is selected with pattern matching and guards. Guards do not permit general expressions, because of some technical issues (what to do about side-effects in a guard that fails?) and because guard operations "should be fast".

If your expressions are restricted to guards, you can write the above with this scheme:

if
    Guard1 -> Expr1;
    Guard2 -> Expr2;
    true   -> Expr3
end

If you need general expressions rather than guards, you probably will have to write it with nested case-expressions (or maybe abuse try). 

case Expr1 of
   true -> Expr2;
   _ -> case Expr3 of ... end
end

or perhaps refactor the whole test into a new function.

There is a proposal to introduce 'cond', which looks like an 'if' with general expressions in the guard position, but it has remained on the bench for a couple of years now. I think the basic issue of contention there is variable scoping.

Consider this example (which I hope is proper cond-syntax):

cond
   {ok, X} = f(Y) -> g(X);   %% clause 1
   true -> h(X)              %% clause 2
end

Should the X bound in clause 1 be visible in clause 2? The current proposal says yes, because you then won't have to repeat some computations in multiple guards. Others (including me) say no, because Erlang scoping normally doesn't work that way.

Also, another reason for not having cond already is that there has been, in practice, fairly low demand for it.

Best,
Thomas




      




More information about the erlang-questions mailing list