case
In Elixir, a case takes one value and tries several patterns against it, from the top. It is the shape a reader reaches for when the value is the thing being decided: a result tuple that may be ok or an error, a message that may be one of three commands, a tag with a body. The patterns are the ones the previous lesson built, and the whole form is an expression with a value.
One value, several shapes
Each arm is a pattern, an arrow and the expression that runs when the pattern fits. The first arm that fits decides the value of the whole case, and the arms below it are not tried. An ok-or-error result is the usual first example:
response.exs
response = {:ok, 42} result = case response do {:ok, body} -> body {:error, reason} -> {:failed, reason} end IO.inspect(result)
elixir response.exs
42
The names inside an arm bind only in that arm. body does not exist in the error arm, and reason does not exist after end; a name that both arms need is returned from each, as result does here. That is also why a case reads well as a function body: the value of the arm is the value of the function.
A guard on an arm
An arm may add a when guard, the same one a function clause takes. The pattern matches first, then the guard decides whether the arm may run; a failed guard moves on to the next arm as if the pattern had not matched:
grade.exs
score = 85 label = case score do n when n >= 90 -> :excellent n when n >= 70 -> :good _ -> :needs_work end IO.puts(label)
elixir grade.exs
good
The arms are read from the top, so the narrower ranges come first. A guard that names a function outside the guard-safe set is a compile error, and the guards lesson lists the set and shows that error. For a chain of unrelated conditions rather than one value, cond reads better than a case whose arms all use _.
_ is the catch-all
A lone underscore matches any value and binds nothing. It is how a case says "everything else", and it belongs last, after every specific arm has had its turn:
catch.exs
input = :quit case input do :go -> IO.puts("moving") _ -> IO.puts("stopped") end
elixir catch.exs
stopped
Without the underscore this value would have no arm, which is the mistake of the last section. A named catch-all such as other works too and lets the body use the value; the underscore is the clearer choice when the value is not needed.
The arm is the value
A case is an expression, so its result can be assigned, piped or returned directly. There is no fall-through and no break: the arm that ran produced the value, and the rest of the program sees only that value. This is the same rule as if, with several shapes instead of two branches.
The mistake: no arm matches
A case without a catch-all trusts that the arms cover every value it will see. When one is not covered, the program stops with a CaseClauseError that names the value:
nomatch.exs
case 5 do 1 -> :one end
elixir nomatch.exs
** (CaseClauseError) no case clause matching:
5
nomatch.exs:1: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2
The fix is either the arm that was forgotten or a final _ arm that handles the rest. A case over a closed set, such as the two shapes of a result tuple, can leave the catch-all out on purpose: the crash is then the report of a value that should never have arrived. A case over open input, such as a line a user typed, needs the catch-all.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which arm of a
caseruns?Answer
The first one whose pattern, and guard, fits the value
The arms are tried from the top and the first fit wins; later arms are not tried.
-
What does the
_arm of acasedo?Answer
It matches any value and binds nothing
The underscore is the catch-all pattern, which is why it goes last.
-
What happens when no arm of a
casematches?Answer
It raises CaseClauseError and shows the value
A case without a matching arm is a run-time error, not a nil result.
-
When is
conda better fit thancase?Answer
When the arms are unrelated conditions rather than shapes of one value
A case decides one value by shape; cond chains independent conditions.
-
What does this program print?
IO.puts(case {:ok, 3} do {:ok, n} -> n * 2 {:error, _} -> 0 end)Answer
6
The first arm binds n to 3, and the arm returns 6.
-
What does this program print?
IO.puts(case 10 do n when n > 5 -> :big _ -> :small end)Answer
big
The guard n > 5 is true, so the first arm runs and the catch-all is not tried.
-
What does this program do?
case 2 do 1 -> :one endAnswer
A CaseClauseError, because no arm matches 2
The only arm fits 1, and a case with no fitting arm raises at run time.
-
What does this program print?
IO.puts(case :x do :a -> 1 _ -> 0 end)Answer
0
The atom :x does not match :a, so the catch-all arm returns 0.
-
What does this program print?
value = case {1, 2} do {a, b} -> a + b end IO.puts(value)Answer
3
The arm destructures the tuple and sums the two elements, and the case returns 3.
-
Where may the names bound in a
casearm be used?Answer
Only in that arm
Each arm has its own scope; a value both arms need is returned from each of them.
Article author: Arthur Isaev