How to make the equivalent of a C-style if-else statement in Erlang?
Solution 1
if
a == b ->
expr1;
true ->
exprElse
end
There is no real else in Erlang, you just match with true. More information at the Erlang documentation.
You have to pay close attention to the ';' terminator :
if
a == b ->
clauseN,
expr1;
cond2 ->
clause1,
clause2,
expr2;
cond3 ->
expr3;
true ->
exprElse
end
It's not a copy-paste friendly language.
Solution 2
Pattern matching is one of Erlangs many strengths and it can often be used instead of if statements. It is often more readable to pattern match on function arguments or use a case expression (which also is pattern matching).
Suppose you have a function some_function
which takes two arguments. If the arguments are equal you evaluate expression1, otherwise you evaluate expression2. This can be expressed in erlang as:
some_function(A, A) -> expression1;
some_function(A, B) -> expression2.
It is quite amazing how much you can achieve with this kind of simple pattern matching. With guard clauses you can express more complicated patterns, e.g.,
some_function(A, B) when A < B -> expression3.
Another possibility is to use a case .. of
expression. Your particular example would translate to
case a == b of
true -> expression1;
false -> expression2
end.
(In this case expression2
would always be evaluated since a
and b
are atoms and never equal to each other. Variables in Erlang are upper case.)
You can read more about Erlang expressions here.
Solution 3
if
A =:= B ->
expr1;
true ->
expr2
end
or
case A =:= B of
true -> expr1;
false -> expr2
end
or
case A of
B -> expr1;
_ -> expr2
end
or
foo(A,B), ...
...
foo(X,X) -> expr1;
foo(_,_) -> expr2.
Solution 4
Another option:
case a of
b -> expr1; %% true
_ -> expr2 %% false
end.
Related videos on Youtube
Abhimanyu
Updated on July 09, 2022Comments
-
Abhimanyu over 1 year
How do I make the equivalent of a C-style if-else in Erlang?
if(a == b) { expression1 } else { expression2 }
-
mrjohnsly almost 15 yearsI'd also suggest using
=:=
instead of==
. This is a really good answer - new erlang programmers should always usecase
until they figure out why theif
statement should have been thewhen
statement. -
Tommy about 8 yearsisn't the equality operator in Erlang
=:=
? -
Talespin_Kit about 8 yearsAlso note that it is an error if none of the conditions match, hence the true clause as the end as a fall through.
-
Electric Coffee about 8 years@Tommy Erlang also has
==
,==
means equal to,=:=
means exactly equal to, kinda like JavaScript's===