If Else in Erlang
Branching with if and case in Erlang is straightforward. Here’s a basic example:
main() ->
if
7 rem 2 =:= 0 ->
io:format("7 is even~n");
true ->
io:format("7 is odd~n")
end.You can have an if statement without an else clause by using true as the final condition:
if
8 rem 4 =:= 0 ->
io:format("8 is divisible by 4~n");
true -> ok
end.Logical operators like andalso and orelse are often useful in conditions:
if
(8 rem 2 =:= 0) orelse (7 rem 2 =:= 0) ->
io:format("either 8 or 7 are even~n");
true -> ok
end.In Erlang, we often use pattern matching and case statements for more complex conditionals:
Num = 9,
case Num of
N when N < 0 ->
io:format("~p is negative~n", [N]);
N when N < 10 ->
io:format("~p has 1 digit~n", [N]);
N ->
io:format("~p has multiple digits~n", [N])
end.Note that in Erlang, you don’t need parentheses around conditions, but each clause in an if or case statement must end with a semicolon, except for the last one which ends with end.
To run this program:
$ erlc if_else.erl
$ erl -noshell -s if_else main -s init stop
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digitIn Erlang, there’s no direct equivalent to the ternary operator, but you can use short case statements or functions for similar concise conditional expressions.