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?
-
[Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236) – EJoshuaS - Stand with Ukraine Feb 27 '17 at 23:34
-
1In what type is `
` being represented? Could you give as an example of code? – Asier Azkuenaga Feb 28 '17 at 07:20 -
-define(IF(E1,E2,E3), case E1 =:= 1 of true -> E2; false -> E3 end). how about this? – kevin Feb 28 '17 at 09:17
-
`case e1 of 0 -> e2; _ -> e3 end.` – juan.facorro Feb 28 '17 at 10:44
-
Do you intend `0.0` to count as `0` as well? Note that this will have an impact on possible solutions, as floating point zero will not match an integer 0, but it can be compared using `==`. – evnu Feb 28 '17 at 20:47
2 Answers
2 remarks:
0
andnot 0
are not the usual values used for boolean expressions, in erlang they are the atomstrue
andfalse
.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?
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).

- 26,174
- 5
- 52
- 73