[erlang-questions] conditional expressions

Richard Carlsson richardc@REDACTED
Sat Nov 15 12:49:58 CET 2008


damien morton wrote:
> I keep wanting to have python-like boolean expression evaluation, in 
> which a value of nil, 0, an empty list or an empty tuple are considered 
> to be false.
> 
> It would be great to have a consise way of saying "the value of this 
> expression is expr1 if expr1 evaluates to a non-false value, or expr2 
> otherwise".
> 
> In python, you would say "X = foo() or bar()", which would evaluate 
> foo(), and if that evaluates to one of None,False,0,[],(),{}, then 
> evaluate bar()

Well, andalso/orelse (as someone suggested) don't work since they
require that expr1 and expr2 evaluate to booleans and nothing else.

> I cant for the life of me figure out what the most concise way of 
> stating that is in erlang.
> 
> perhaps
>  X = if (T1=foo()) =/= [] -> T1, false -> bar() end
> 
> it would nice to be able to say something like
>  X = foo() otherwise bar().

X = case foo() of
       [] -> bar();
       X1 -> X1
     end

If you need to check for other values as well, replace '[] ->' with
'X when X =:= [] ; X =:= 0 ; ... ->'

But I've always felt that this feature of Python/Perl/... boils down
to sloppy programming style. It basically means that the caller hopes
that the "empty or failure" case is signalled by one of the values
reconized as pseudo-booleans by the language (the programmer might
not actually know the exact interface of the called function, but
guessed that this would work), and the resulting code says nothing to
the reader about the actual set of return values. Furthermore, the
code might do the wrong thing if the function tries to return e.g. '0'
or '{}' on success (as opposed to False or None or whatever it usually
uses for failure). It simply makes the code a lot less tight than it
ought to be. And then, you still can't use the same idiom on abstract
data types to treat e.g. an empty set as "false".

     /Richard



More information about the erlang-questions mailing list