Description
The reason the ternary operator _ ? _ : _
_ ? _ : _
exists in many languages, due to the fact that they have two syntactic classes: expressions and expressions. Since if-then-else constructs usually belong to the statement class, there is no way to get this when you enter an expression. Therefore, you add the _ ? _ : _
operator _ ? _ : _
_ ? _ : _
to the expression class.
As another message state, can you take a == b ? true : false
a == b ? true : false
and just write a == b
, but that does not explain the general case when we can have a == b ? X : Y
a == b ? X : Y
for arbitrary expressions X
and Y
Also note that a == b
always false
in Erlang, so you can argue that the real task is to replace the entire expression with false
.
Fortunately, Erlang, like most functional languages, has only one syntax class, expressions. Therefore, you can use case a == b of X -> ...; Y -> ... end
case a == b of X -> ...; Y -> ... end
anywhere in the function, including other expressions. In other words, the ternary operator _ ? _ : _
_ ? _ : _
redundant in Erlang since case
already running.
Example:
Suppose we need to return a simple leaflet and we need to figure out what we need to do
f() -> case a == b of true -> [{a, 3}, {b, <<"YE">>}, {c, 7}]; false -> [{a, 3}, {b, <<"YE">>}, {c, "HELLO!!!"}]; end.
But since the case
construct is an expression, we can simply insert it:
f() -> [{a, 3}, {b, <<"YE">>}, {c, case a == b of true -> 7; false -> "HELLO!!!" end}].
and run with the thing.
Why I'm not a fan of using IF
The if .. end
construct in Erlang is usually not what you want. In this case, you want to examine the value a == b
, and it can give one of two outputs true
or false
. In this case, the case expression is more direct. if
better to use if you need to test several different tests and select the first match, whereas we only have one test to do here.