Ternary operator used as assert

Attila Rajmund Nohl attila.r.nohl@REDACTED
Tue Dec 22 12:18:37 CET 2009


Hello!

There was a recent thread here about how to implement a C-style "?:"
code in Erlang. My code would look something like this in C:

strlen(X)==0 ? OK : return X[0];

My very naive generic Erlang implementation is this:

assert(true, Val, _) ->
    Val;
assert(false, _, Val) ->
    Val.

And the call would be this:

assert(X == [], ok, hd(X)).

Of course, this doesn't work if the list X is actually empty. The
hd(X) is evaluated even if the X list is empty and the code crashes.
This is a big difference to the C code where the "else" branch is not
executed. Is there an elegant, one liner solution?


More information about the erlang-questions mailing list