Elixir Case Expressions
A case expression matches a value against patterns in order. The first pattern that matches gives the result of the whole expression.
A tuple pattern binds the value inside
Each branch gives a pattern, an arrow, and a result. The ok tuple fits the first pattern, and value binds 42.
result = {:ok, 42}
message =
case result do
{:ok, value} -> "got #{value}"
{:error, reason} -> "failed: #{reason}"
end
IO.puts(message)A map pattern checks only the keys it names
A map pattern matches when the named keys hold the given values. The rest of the map is ignored.
user = %{name: "Ana", role: :admin}
access =
case user do
%{role: :admin} -> "full access"
%{role: :guest} -> "guest access"
_ -> "no access"
end
IO.puts(access)An exact pattern placed first beats the fallback
The _ pattern would match 404 too. The exact branch wins because it comes first.
code = 404
label =
case code do
404 -> "not found"
_ -> "other code"
end
IO.puts(label)Example
items = [150, 250]
report =
case items do
[] -> "cart is empty"
[only] -> "one item: #{only}"
[first, second] -> "two items: #{first} and #{second}"
_ -> "many items"
end
IO.puts(report)Key points
- Pattern: the shape on the left of an arrow that a value must fit to take that branch.
- Order: branches are tried from top to bottom, and the first match wins.
- Binding: a variable in a pattern binds the part of the value it matches.
- Fallback: the _ pattern matches any value and catches what earlier branches miss.
- Result value: a case expression returns the result of the branch that matched.
- Any shape: patterns can match tuples, lists, and maps, not only single values.
In this example, the list holds two items, so the empty and one-item patterns fail. The two-item pattern matches and binds first to 150 and second to 250.
Note
a case with no matching branch raises an error, so a _ fallback keeps it safe.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does case :error do :error -> "failed"; _ -> "other" end return?