[erlang-questions] Ternary operator used as assert

Robert Virding rvirding@REDACTED
Tue Dec 22 13:12:38 CET 2009


A better alternative would be a macro:

-define(ASSERT(TEST,TRUE,FALSE), case TEST of true -> TRUE; false -> FALSE
end).

which shouldn't create any compiler warning/errors unless either TRUE or
FALSE contains code which is not always valid. Using 'if' is an alternative
if the test is a guard test.

Robert

2009/12/22 Zoltan Lajos Kis <kiszl@REDACTED>

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


More information about the erlang-questions mailing list