Reputation: 1
I have conditional expressions <e1?e2:e3>
. If e1 evaluates to zero, then the whole expression evaluates to the value of e2, and if e1 evaluates to anything else, the whole expression has the value of e3. Could someone help point me in the right direction of how to add conditional expressions?
Upvotes: 0
Views: 72
Reputation: 26121
case E1 =:= 0 of
true -> E2;
_ -> E3
end
if E1 is expression allowed in guard it will generate exactly same bytecode as
if E1 =:= 0 -> E2;
true -> E3
end
You could make it as macro:
-define(IF(E1, E2, E3), case E1 =:= 0 of
true -> E2;
_ -> E3
end).
Upvotes: 1
Reputation: 14042
2 remarks:
0
and not 0
are not the usual values used for boolean expressions, in erlang they are the atoms true
and false
.
Although it is possible to define a macro with parameters, it is not very usual to share those macros, via include files, between many modules. The exceptions are the record definitions within the scope of an application or a library.
I think that the 2 common ways to code this choice are either directly in the code:
Result = case E1 of
0 -> E2;
_ -> E3
end,
either define a local function:
choose(0,E2,_) -> E2;
choose(_,_,E3) -> E3.
...
Result = choose(E1,E2,E3),
of course (despite of my second remark that implies that you will repeat the macro definition again and again) you can code the first one with a macro:
-define(CHOOSE(E1,E2,E3),case E1 of 0 -> E2; _ -> E3 end).
...
Result = ?CHOOSE(E1,E2,E3),
see also this topic: How to write “a==b ? X : Y” in Erlang?
Upvotes: 2