[erlang-questions] Ternary operator used as assert

Zoltan Lajos Kis kiszl@REDACTED
Tue Dec 22 12:41:59 CET 2009


You can wrap the return values in functions:

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

assert(X == [], fun() -> ok end, fun() -> hd(X) end).


A macro can also be used for the wrapping:

-define(ASSERT(EXPR, T, F), assert(EXPR, fun() -> T end, fun() -> F end)).

?ASSERT(X == [], ok, hd(X)).

Apparently the compiler will emit warnings for hd(X). Nevertheless, the 
code works.

Regards,
Zoltan.

Attila Rajmund Nohl wrote:
> 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?
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>   



More information about the erlang-questions mailing list