iex> cond do
...> 2 + 2 == 5 -> # 1 if expression (equivalent)
...> "This is never true" # 1
...> 2 * 2 == 3 -> # 2 if-else expression (equivalent)
...> "Nor this" # 2
...> true -> # 3 else expression (equivalent)
...> "This is always true (equivalent to else)" # 3
...> end
"This is always true (equivalent to else)"
It’s important to remember that cond
, case
and even if
are expressions , not statements (i.e. not control flow structures) - think: ternary operator in JavaScript, (C, C++, C#, Java) - i.e. they are fundamentally designed to return a value - though the compiler doesn’t yell at you if you ignore the returned value. Functions with multiple clauses work similarly as functions always return values. Many situations can be implemented with either case
expressions or multi-clause functions and both support guards which is essentially is a condition that refines the pattern match.