liveBook · Manning

Multiclause function

As explained in Elixir in Action, Third Edition

A multiclause lambda is an anonymous function composed of multiple clauses selected according to their patterns and optional guards.

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

How Elixir in Action, Third Edition covers it

How deep it goes
Explains argument matching, clause order, guards, fallback errors, function capture, lambdas, and recursive use cases.
Examples
Demonstrates geometry dispatch, numeric classification, list-shape tests, polymorphic doubling, factorial, list summation, and recursive number printing.
What it assumes
Assumes basic Elixir functions and requires understanding pattern matching before clause-based control flow.
What you can do after
Build pattern-directed named and anonymous functions that branch on values, types, and data shapes.
How it connects
Connects pattern matching, guards, conditional expressions, recursion, higher-order functions, and tail-call optimization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.