A multiclause function defines several clauses with the same name and arity. Elixir matches the call’s arguments against each clause in source order and executes the first complete match, making pattern matching a direct control-flow mechanism. section 3.2 section 3.2.1
Use clauses to express distinct input shapes, values, and outcomes:
- Match structured data directly, such as rectangles, squares, and circles represented by tagged tuples. section 3.2.1
- Add guards when patterns alone cannot express a condition, such as distinguishing negative, zero, and positive numbers. section 3.2.3
- Provide a final variable-pattern clause when invalid input should return an error tuple instead of raising FunctionClauseError. section 3.2.1
- Treat all clauses as one function when capturing it with &Module.fun/arity; callers cannot select an individual clause. section 3.2.1
Dispatch by shape
def area({:rectangle, a, b}), do: a * b def area({:square, a}), do: a * a def area({:circle, r}), do: r * r * 3.14 Geometry.area({:square, 5}) returns 25. An unmatched tuple raises FunctionClauseError unless a final fallback clause handles it. section 3.2.1
iex(3)> test_num =
fn
x when is_number(x) and x < 0 -> :negative
x when x == 0 -> :zero
x when is_number(x) and x > 0 -> :positive
end
A guarded anonymous function classifies numbers through multiple clauses, illustrating the fn syntax used when clause-based dispatch is passed as a value. section 3.2.3
Multiclause functions also replace many conditionals and support polymorphic behavior: clauses can distinguish numbers from binaries, empty lists from nonempty lists, or recursion base cases from recursive cases. Recursion supplies loop structure when no loop statement is available. section 3.3.1 section 3.4.1
