Elixir case, cond and if
Elixir has three main ways to choose between branches. Each one is an expression: it returns a value, so you can assign its result to a variable.
| Construct | Chooses a branch by… | Typical use |
|---|---|---|
case |
matching a value against patterns | results like {:ok, x} / {:error, reason} |
cond |
the first condition that is truthy | several unrelated conditions |
if / unless |
a single condition | simple yes/no decisions |
case
case tries each pattern from top to bottom and runs the first one that matches. Clauses may have a guard (when ...) for extra conditions:
describe = fn response ->
case response do
{:ok, 200, body} -> "OK: #{body}"
{:ok, status, _body} when status in 300..399 -> "redirect (#{status})"
{:ok, status, _body} -> "HTTP error #{status}"
{:error, reason} -> "failed: #{reason}"
end
end
IO.puts(describe.({:ok, 200, "welcome"}))
IO.puts(describe.({:ok, 301, ""}))
IO.puts(describe.({:ok, 404, "not found"}))
IO.puts(describe.({:error, :timeout}))OK: welcome
redirect (301)
HTTP error 404
failed: timeout
If no clause matches, Elixir raises a CaseClauseError. Add a catch-all clause _ -> ... when you want a default.
try do
case :maybe do
:yes -> "yes"
:no -> "no"
end
rescue
e in CaseClauseError -> IO.puts(Exception.message(e))
endno case clause matching:
:maybe
Guards
Guards are restricted to a set of expressions that are fast and have no side effects: comparisons, and/or/not, arithmetic, in, type checks such as is_integer/1, and functions like length/1, map_size/1, rem/2, abs/1. You cannot call your own functions inside a guard (but you can define guard macros with defguard, covered in the Guards lesson).
cond
cond is like an else if chain. It evaluates each condition in turn and runs the body of the first one that is truthy. Use true as the last condition for a default:
bmi_label = fn bmi ->
cond do
bmi < 18.5 -> "underweight"
bmi < 25 -> "normal"
bmi < 30 -> "overweight"
true -> "obese"
end
end
for value <- [17.0, 22.4, 27.9, 31.2] do
IO.puts("#{value}: #{bmi_label.(value)}")
end17.0: underweight
22.4: normal
27.9: overweight
31.2: obese
If no condition is truthy, cond raises a CondClauseError, so the true -> clause is almost always there.
if and unless
if takes one condition. Only false and nil are falsy. Without an else, a false condition returns nil. unless is the inverse of if.
stock = 0
message = if stock > 0, do: "in stock", else: "sold out"
IO.puts(message)
IO.inspect(if stock > 0, do: "available")
unless stock > 0 do
IO.puts("Reorder this item")
end
# 0 and "" are truthy in Elixir
if 0, do: IO.puts("0 is truthy")sold out
nil
Reorder this item
0 is truthy
The one-line form if cond, do: a, else: b is just a keyword list (do: and else:), and do ... end blocks are syntax sugar for it.
Variables and scope
Variables bound inside a branch do not leak out. Instead, return the value from the expression:
temperature = 31
# Don't: bind inside the if and hope it is visible later.
# Do: use the result of the if expression.
advice =
if temperature > 30 do
"stay hydrated"
else
"enjoy the weather"
end
IO.puts(advice)stay hydrated
Which one to pick
- Matching on the shape of data (tagged tuples, maps, lists):
case. - Several boolean conditions on different things:
cond. - A single condition:
if. - In functions, multiple function clauses with patterns and guards are often clearer than any of them (see the Function Clauses lesson).
Test yourself
What does if false, do: :yes return?
:nofalsenil- It raises an error
What happens when no clause of a case matches?
- It returns nil
- It raises a CaseClauseError
- It runs the last clause
- It returns the original value
Which values are falsy in Elixir?
false,nil,0and""- Only
false falseandnilfalse,niland[]