[erlang-questions] Ternary operator used as assert
Zoltan Lajos Kis
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
Attila Rajmund Nohl wrote:
> 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;
> My very naive generic Erlang implementation is this:
> assert(true, Val, _) ->
> assert(false, _, 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