liveBook · Manning

Pattern matching

As explained in Elixir in Action, Third Edition

Pattern matching is a language mechanism that compares a value with a pattern and succeeds when their structure and contents conform, binding variables in the pattern.

Pattern matching compares a term with a pattern. A successful match binds variables to corresponding parts of the term and returns the matched term; a failed match raises an error. In Elixir, this mechanism replaces much assignment-style code and supports branching, data decomposition, and recursion. section 3.1 section 3.1.9

Use patterns to express structural expectations directly:

  • Destructure tuples such as {name, age}, including nested date and time tuples. section 3.1.2
  • Match constants inside compound terms, such as {:person, name, age} or {:ok, contents}, to validate tagged results while extracting values. section 3.1.3
  • Decompose lists with [head | tail], ignore fields with _, and constrain repeated variables when the structure requires it. section 3.1.5
  • Split binaries into bytes, bit fields, or a fixed prefix and remaining binary, which supports packed-data parsing. section 3.1.7

Dispatch with multiclause functions

Function arguments are patterns, so clauses can branch on the shape and values of input without nested conditionals. Clauses are tested in source order, and the first complete match runs. A final variable-pattern clause can convert unknown input into an explicit {:error, reason} result instead of raising a FunctionClauseError. section 3.2 section 3.2.1 section 3.3.1

Chain fallible operations with with

Use with when several operations return tagged results such as {:ok, value} or {:error, reason}. Each expression is matched in sequence; success continues to the next expression, while the first unexpected result is returned immediately. This keeps validation and normalization flatter than nested case expressions. section 3.3.3

Pattern matching also supplies the base cases and recursive shapes used for iteration. An empty list can terminate a function, while [head | tail] can consume one element and recurse over the remainder. Tail recursion supports arbitrarily long loops when the recursive call is arranged appropriately. section 3.4.1 section 3.5

Listing 3.2 Multiclause function (geometry.ex)
defmodule Geometry do
  def area({:rectangle, a, b}) do     #1
    a * b
  end
 
  def area({:square, a}) do           #2
    a * a
  end
 
  def area({:circle, r}) do           #3
    r * r * 3.14
  end
end

Compare shape-based clauses for rectangles, squares, and circles in a compact runnable function. section 3.2.1

Listing 3.6 with-based user extraction (user_extraction.ex)
def extract_user(user) do
 with {:ok, login} <- extract_login(user),
      {:ok, email} <- extract_email(user),
      {:ok, password} <- extract_password(user) do
   {:ok, %{login: login, email: email, password: password}}
 end
end

Trace a production-shaped user extraction pipeline that matches successful field lookups and preserves descriptive failures. section 3.3.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains tuple, list, binary, nested, chained, constant, function-argument, and with-pattern behavior, while deferring the complete pattern reference.
Examples
Demonstrates people tuples, calendar values, file reads, binary commands, geometry dispatch, user extraction, and recursive list processing.
What it assumes
Assumes familiarity with Elixir’s basic building blocks and tuple and list structures, while introducing the non-assignment behavior of =.
What you can do after
Apply it to destructure data, dispatch functions by input shape, compose tagged operations, and implement recursive list processing.
How it connects
Connects the match operator with tuples, lists, binaries, multiclause functions, guards, with expressions, recursion, and tagged results.

Also explained in

Compare how 12 books explain pattern matching →

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.