Elixir Function Clauses & Guards
A named function can have several clauses. Each clause has its own pattern in the argument list and an optional guard. When the function is called, Elixir tries the clauses from top to bottom and runs the first one that matches. Writing functions this way replaces most if/case code with small, declarative definitions.
defmodule Shipping do
def cost(:standard, weight) when weight <= 2, do: 4.99
def cost(:standard, _weight), do: 7.99
def cost(:express, weight), do: 9.99 + weight * 1.5
def cost(:pickup, _weight), do: 0
end
IO.inspect(Shipping.cost(:standard, 1))
IO.inspect(Shipping.cost(:standard, 5))
IO.inspect(Shipping.cost(:express, 2))
IO.inspect(Shipping.cost(:pickup, 30))4.99
7.99
12.99
0
Order matters
Clauses are tried in order, so put the specific ones first and the general ones last. If a general clause comes first, the specific one can never match, and the compiler warns you about it:
defmodule Fib do
def of(0), do: 0
def of(1), do: 1
def of(n) when is_integer(n) and n > 1, do: of(n - 1) + of(n - 2)
end
IO.inspect(Enum.map(0..10, &Fib.of/1))
try do
Fib.of(-3)
rescue
e in FunctionClauseError -> IO.puts(Exception.message(e))
end[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
no function clause matching in Fib.of/1
When no clause matches, Elixir raises FunctionClauseError. That is usually what you want: invalid input fails loudly at the boundary instead of producing a wrong result later.
What can go in a guard
Guards only allow a fixed set of expressions, so they are guaranteed to be fast and free of side effects.
| Category | Allowed |
|---|---|
| Type checks | is_integer/1, is_float/1, is_number/1, is_binary/1, is_atom/1, is_list/1, is_map/1, is_tuple/1, is_boolean/1, is_nil/1, is_function/2, is_struct/2 |
| Comparison & logic | ==, !=, ===, <, >=, …, and, or, not, in (with a literal list or range) |
| Arithmetic | +, -, *, /, div/2, rem/2, abs/1, round/1, trunc/1 |
| Sizes and elements | length/1, map_size/1, tuple_size/1, byte_size/1, elem/2, hd/1, tl/1, is_map_key/2 |
If a guard raises an error (for example length/1 on a non-list), the guard simply fails and the next clause is tried; no exception escapes.
defmodule Classify do
def kind(x) when is_integer(x) and rem(x, 2) == 0, do: "even integer"
def kind(x) when is_integer(x), do: "odd integer"
def kind(x) when is_float(x), do: "float"
def kind(s) when is_binary(s) and byte_size(s) == 0, do: "empty string"
def kind(s) when is_binary(s), do: "string"
def kind(l) when length(l) > 0, do: "non-empty list"
def kind(_), do: "something else"
end
for v <- [4, 7, 2.5, "", "hi", [1, 2], [], :ok] do
IO.puts("#{inspect(v)} -> #{Classify.kind(v)}")
end4 -> even integer
7 -> odd integer
2.5 -> float
"" -> empty string
"hi" -> string
[1, 2] -> non-empty list
[] -> something else
:ok -> something else
For :ok, the guard length(l) > 0 raises internally because :ok is not a list. The guard just fails and the catch-all clause handles it.
Multiple guards and custom guards
You can chain several when conditions (each one is an alternative, like or), and you can name a reusable guard with defguard:
defmodule Calendar2 do
defguard is_weekend(day) when day in [:sat, :sun]
def opening_hours(day) when is_weekend(day), do: "10:00-16:00"
def opening_hours(:fri), do: "09:00-20:00"
def opening_hours(day) when day in [:mon, :tue, :wed, :thu], do: "09:00-18:00"
def label(x) when is_integer(x) when is_float(x), do: "number"
def label(_), do: "not a number"
end
IO.puts(Calendar2.opening_hours(:sun))
IO.puts(Calendar2.opening_hours(:fri))
IO.puts(Calendar2.opening_hours(:tue))
IO.puts(Calendar2.label(1.5))
IO.puts(Calendar2.label("1.5"))10:00-16:00
09:00-20:00
09:00-18:00
number
not a number
defguard creates a macro that can be used in guards; define it before the functions that use it. To use a guard from another module, import or require that module.
Matching in the argument list
Patterns in function heads can destructure anything: tuples, maps, structs, lists and binaries. You can also bind the whole argument with = while matching parts of it:
defmodule Orders do
def summary(%{status: :paid, total: total} = order) do
"##{order.id} paid #{total} EUR"
end
def summary(%{status: status, id: id}), do: "##{id} is #{status}"
end
IO.puts(Orders.summary(%{id: 1, status: :paid, total: 30}))
IO.puts(Orders.summary(%{id: 2, status: :pending, total: 12}))#1 paid 30 EUR
#2 is pending
Test yourself
What happens when no function clause matches the arguments?
- The function returns nil
- A FunctionClauseError is raised
- The last clause runs anyway
- A compile error
What happens when an expression inside a guard raises an error?
- The program crashes
- The guard fails and the next clause is tried
- The error is returned
- It's a compile error
Why should general clauses come after specific ones?
- For performance only
- Because clauses are tried top to bottom, so a general clause first would always win
- Because Elixir sorts clauses alphabetically
- It doesn't matter