Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 25 — Pattern Matching Deep Dive: How = Really Works

Pattern matching is the reflex you will use more than any other feature in Elixir — this chapter expands my dev.to article on the topic into the full mechanics: what = actually does, how a match executes step by step, everywhere patterns can appear, what the compiler builds from them, and the rules for maps and binaries that most tutorials skip.

From Erlang you know: the matching semantics are identical — structural unification over terms, selective receive, function-clause dispatch, the same binary-segment syntax. One difference changes how you read every line of Elixir code: variables are rebindable, so a bound variable in an Erlang pattern compares, while in Elixir it would rebind — hence the pin operator ^. Everything else transfers intact.

The three verbs from the article still organize everything:

  1. Check — assert a value’s shape or exact content ({:ok, "hello"} = {:ok, "hello"}).
  2. Extract — pull parts out of a complex term ({:ok, value} = tuple).
  3. Dispatch — choose behavior by shape (function clauses, case, receive).

And its summary of the operator holds verbatim: = always evaluates the right-hand side, tries to make it fit the pattern on the left, returns the right-hand term so expressions compose, and raises MatchError when no fit exists:

result = {:ok, {total, items} = payload} = {:ok, {1, ["hi"]}}
#=> {:ok, {1, ["hi"]}}

payload
#=> {:ok, {1, ["hi"]}}      captured mid-chain too
total
#=> 1

One expression, three bindings: result, payload, then total/items — because matching nests like the terms do.

25.1 = Is Unification With Rebinding

In Erlang, = performs single-assignment unification: once X is bound, X = 5 compares. In Elixir, = matches the pattern against the term; a bare variable in the pattern binds or rebinds:

expected = 2
{^expected, tag} = {2, :b}    # ^compares: only matches if expected == 2
{expected, tag} = {99, :c}    # no pin: REBINDS expected to 99

The pin is compile-time sugar for “compare against this variable’s current binding,” and it composes anywhere a variable can appear:

%{id: ^user_id} = record
[<<^header, _::binary>>] = frames

Two relatives complete the family:

Pattern pieceBehavior
valuebinds or rebinds
^valuecompares against existing binding
_consumes anything, binds nothing, reusable freely
_reasondoes bind — naming for readability, warnings suppressed

That last row trips people: _reason is a real variable. Only bare _ refuses to bind, which is why _ = 1 followed by _ = :anything is fine.

Chained matches flow the term right-to-left through every pattern; all must accept it, and each gets to extract:

list = {:ok, {:waiting, [1, 2, 3]}, {:running, [4, 5, 6]}}

{:ok, _, _} = {_, {:waiting, list1}, _} = {_, _, {:running, list2}} = list

list1
#=> [1, 2, 3]
list2
#=> [4, 5, 6]

25.2 How a Match Executes

Conceptually the runtime walks the pattern and the term together, top-down:

flowchart TD
    START["pattern = term<br/>right side evaluated first"] --> KIND{"what is this<br/>pattern part?"}
    KIND -->|"bare variable"| BIND["bind the value"]
    KIND -->|"underscore"| SKIP["consume, bind nothing"]
    KIND -->|"pin caret name"| CMPV["compare against<br/>current binding"]
    KIND -->|"literal"| CMPL["structural equality check"]
    KIND -->|"tuple · list · map · struct"| DESCEND["descend into the shape"]
    CMPV --> PART
    CMPL --> PART
    BIND --> PART["part matched"]
    SKIP --> PART
    DESCEND --> KIND
    PART --> MORE{"parts remaining?"}
    MORE -->|"yes"| KIND
    MORE -->|"no"| DONE["success: expression returns<br/>the term - else MatchError"]

Rules worth internalizing because they explain otherwise-surprising errors:

  • Shape must agree exactly. Tuples encode arity: {_, _, _} matches only 3-tuples. Lists decompose head/tail, with the tail holding the remainder:

    [a | b] = [1, 2]   #=> a = 1, b = [2]
    [a | b] = [1]      #=> a = 1, b = []
    match?([_ | _], <<1>>)   #=> false — a binary is not a list
    
  • Repeated variables must agree within one pattern. %{a: v, b: v} matches %{a: 10, b: 10} and raises MatchError on %{a: 10, b: 11} — repetition is an implicit equality constraint, because the second v is a match against the first’s binding.

    Note the consequence: you cannot write the pinned form in the same pattern, because ^v is only legal once v is already bound —

    v = 10
    %{a: ^v, b: x} = %{a: 10, b: 11}   # legal: ^v compares against v
    # %{a: v2, b: ^v2} = ...           # CompileError: undefined variable ^v2
    

    Inside one pattern, repetition is the comparison. Across patterns, you pin. That is the whole pin story (Ch 02 §2.7.5).

  • Map patterns are subset matches (next section), tuples are exact-shape matches. Choosing between them is a design decision about strictness.

  • Failure raises immediately — MatchError for =, CaseClauseError for an exhausted case, FunctionClauseError for function dispatch. This is the article’s fail-fast point wired directly into let-it-crash: a bad shape kills the process early with full context instead of poisoning downstream state (Ch 22–24 own the recovery).

25.3 Where Patterns Live

Every construct below accepts full patterns — literals, pins, guards, nesting:

SiteNotes
function headsthe default dispatch style; clauses tried top-down
anonymous fn headssame, inline: fn :ok -> true; _ -> false end
caseone term, many patterns; must handle what can arrive
receivemailbox scan per clause (§22.2’s receive-mark pairs with this)
with <-non-matching value falls through as the result
for generatorsnon-matching elements are silently filtered
%Module{} in argsstruct-kind check plus field extraction
= anywhereassertions mid-expression

Three behaviors distinguish these sites, and mixing them up is a classic bug source:

  • Failure kind. Function dispatch raises FunctionClauseError; case with no matching clause raises CaseClauseError; bare = raises MatchError. Reading production stacktraces is faster when you know which failure means which stage.
  • Fall-through semantics. with returns the first non-matching value (optionally intercepted by else); for skips it silently:
with {:ok, n} <- {:ok, 41},
     {:ok, m} <- {:error, :nope} do
  :unreachable
else
  {:error, reason} -> {:failed, reason}
end
#=> {:failed, :nope}

for {:ok, n} <- [{:ok, 1}, :junk, {:ok, 3}], do: n
#=> [1, 3]          # :junk vanished without a trace
  • Order is semantics. Among overlapping clauses the first match wins, so a catch-all placed early shadows everything after it — and the compiler tells you:
warning: this clause for f/1 cannot match because a previous clause
         at line 87 always matches

The compiler reorders nothing you wrote; it only refuses to compile dead clauses and builds efficient decision trees underneath (25.6). Put specific clauses first, guards to narrow them, and the catch-all last.

Defaults + multiple clauses = explicit header

A function with both \\ defaults and pattern-matched clauses needs a bare header declaring the default once:

defmodule Greet do
  def hello(name, greeting \\ "Hello")

  def hello(nil, _greeting), do: "who?"
  def hello(name, greeting), do: "#{greeting}, #{name}!"
end

Guards extend patterns where patterns run out

Patterns check structure; guards check properties:

def classify(n) when is_integer(n) and n > 0, do: :positive
def classify(n) when is_integer(n), do: :non_positive
def classify(_other), do: :other

And match?/2 answers yes/no without binding — the captured variable stays local to the pattern:

match?({:ok, val}, {:ok, 1})
#=> true        # but `val` does not exist out here - use case/= to extract

25.4 Maps and Structs — Subset vs Kind Matching

Two asymmetries matter constantly:

Map patterns ignore extra keys. %{a: 1} matches any map that has :a => 1, regardless of what else it holds. Missing keys fail; extra keys pass through untouched:

%{a: 1} = %{a: 1, b: 2}
#=> matches

%{missing: _} = %{a: 1}
#=> MatchError

Consequently %{} matches every map — including structs, since structs are maps with a __struct__ key. That makes bare %{} nearly useless as an assertion and occasionally dangerous as a catch-all clause. When you mean “a value of this record type,” name the struct — the kind check comes free alongside field extraction:

%Date{day: day, year: year} = deadline     # checks Date, extracts fields
%Time{} = t                                 # rejects a Date outright

Cost note for hot paths: each key in a map pattern is one lookup, so a pattern naming five keys costs five lookups against maps stored as sorted flat arrays (≤32 keys) or hash-tries (larger). Fine almost everywhere; relevant inside per-message loops.

25.5 Binaries and Bitstrings — the Article’s Core, Extended

The article’s progression is exactly right, and every example below is verified. Bytes first:

bin = <<1, 2, 3, 4, 5>>

<<first, rest::binary>> = bin
#=> first = 1, rest = <<2, 3, 4, 5>>

<<1, second, rest::binary>> = bin          # literal + variable segments mix
#=> second = 2

<<head::binary-size(2), tail::binary>> = bin
#=> head = <<1, 2>>

Bit-level access needs only size specifiers — the same syntax constructs and matches:

bit = <<3::4, 1::4, 3::4, 0::4>>           # 16 bits total

<<first_8::bitstring-size(8), rest::bitstring>> = bit
#=> first_8 = <<3::4, 1::4>>, rest = <<3::4, 0::4>>

<<3::4, next_4::bitstring-size(4), _>> = bit
#=> matches literal 3, extracts the following nibble, drops the last byte

Three extensions turn this from syntax into a working protocol tool.

Sizes can read earlier segments — the pattern is processed left to right, so a length prefix drives the extraction (this single feature replaces most hand-written parsers):

packet = <<11, "hello world">>
<<len, body::binary-size(len)>> = packet
#=> len = 11, body = "hello world"

Sizes must be pinned in patterns. This is the Elixir 1.20 rule that catches everyone writing a parser, and it applies whenever the size comes from a variable bound outside the pattern:

bin = <<1, 2, 3, 4, 5>>
n = 3

<<a::size(n), _::binary>> = bin
#   ~~~~ warning: "the variable n is accessed inside size(...) but it was
#                 defined outside of the match. You must precede it with
#                 the pin operator"
# then MatchError — the compiler treated `n` as a fresh pattern variable

<<a::size(^n), _::binary>> = bin    # correct

In construction the bare variable is fine — <<9::size(n), 0::3>> builds correctly, because there is nothing to compare against. The asymmetry is patterns-compare, construction-compute.

Combined with the tail rules below, <<a::size(^n), rest::binary>> only matches when bit_size(bin) - n is a multiple of 8. Verified: n = 8 matches; n = 3 does not. If the length prefix is in bits, either divide it by 8 yourself or use rest::bits. This is the exact hazard that used to show up as a mysterious MatchError in hand-rolled parsers.

UTF segments decode during matching:

<<"h", é::utf8, rest::binary>> = "héllo"
#=> é = 233, rest = "llo"        - one codepoint, not one byte

Tail types have strict rules, verified against the runtime:

Final segmentMatches remainder of
rest::binarywhole bytes only — fails on non-byte-aligned leftovers
rest::bits / ::bitstringany remainder, down to single bits
match?(<<_::1, t::binary>>, <<31::5>>)     # 4 bits would remain
#=> false - ::binary refuses non-byte-aligned tails

case <<31::5>> do
  <<_::1, t::bits>> -> {:got, bit_size(t)} # => {:got, 4}
end

And the quiet performance win underneath it all: extracting rest does not copy. A sub-binary is an offset-and-length view into the original, so slicing a gigabyte log line costs the same as slicing two bytes — with the caveat that the view pins the whole original in memory until every view is gone; long-lived extractions of huge binaries should be copied explicitly (:erlang.binary_copy/2) or re-encoded.

25.6 Under the BEAM Hood

What the compiler actually builds from your patterns:

  • Function clauses become decision trees. Clauses sharing structure are grouped and tested by tag/type once, then branched — ten clauses matching on %{kind: ...} cost roughly one map-type test plus per-clause key probes, not ten full rescans. Your clause order remains the semantic contract; the trees preserve it while skipping tests that cannot matter.
  • Binary patterns compile to dedicated bit-matching instructions (bs_match family) walking segment by segment; constant prefixes become fast comparisons, dynamic sizes consume earlier bindings.
  • Sub-binaries are views, as above — allocation-free extraction is why protocol parsers written as pattern matches routinely beat hand-rolled index arithmetic.
  • Map patterns lower to keyed lookups, not iteration: no scanning of entries you did not name.
  • receive pairs selective scan with unique refs (22.2): the compiler’s receive-mark optimization exists precisely because function/case-style pattern matching runs over the mailbox too.

From Erlang you know: all of the above machinery is shared — your erl intuition about clause grouping, binary instructions, and sub-binary economics applies unchanged. Only the surface syntax differs, plus the pin operator from Ch 02.

25.7 A Workflow, Not Just Syntax

The article’s closing thought deserves the last word before practice: pattern matching is friendly to your brain because it is declarative — you describe the shape of acceptable data and name its parts, instead of writing the navigation code to reach inside. The habit that compounds:

  1. Assert at boundaries — {:ok, term} = external_result where a wrong shape is a bug you want loud.
  2. Extract with named parts — patterns document structure better than accessors (%{headers: %{"content-type" => ct}} = resp).
  3. Dispatch on shape — function heads over if/is_map_key? chains; each clause is a documented case.
  4. Fail fast and let the tree fix it — every chapter in this part is downstream of this one idea.

Explore More

Checkpoint

  1. What does = evaluate first, what does it return, and what does it raise on failure?
  2. Without running it: does {expected, tag} = {2, :b} change expected, and how would you prevent that?
  3. %{} matches %Date.new!(2026, 8, 26) — why, and what do you write when you want kind safety?
  4. <<len, body::binary-size(len)>> works — why can’t body::binary-size(n) use a variable n bound later in the same pattern?
  5. You need the remainder of a bitstring that may not be byte-aligned. Which tail type, and why does ::binary refuse?
  6. In production logs you see FunctionClauseError. Which constructs were involved, and how is it different from MatchError?
Answers
  1. Right side first; the expression returns the right-hand term; failure raises MatchError.
  2. It rebinds expected to 2 (here harmlessly) — pin it: {^expected, tag} = {2, :b} compares instead of rebinding.
  3. Structs are maps (with a hidden __struct__ key), and map patterns are subset matches. Write the struct pattern %Date{...} to check kind while extracting.
  4. Binary segments are matched left to right, so earlier bindings are available as sizes; a size from a later binding would require solving the layout backwards, which the matcher does not do.
  5. rest::bits (bitstring). ::binary requires a whole number of bytes — e.g., 4 leftover bits fail it but match ::bits.
  6. Function-head dispatch found no accepting clause (function call site); MatchError comes from a bare =/struct-match failing. Same family of shape failures, different stage — which tells you where to look.

Next: Chapter 26 — OTP Wisdom — the last Part V chapter: the judgement the mechanics imply.

Back to table of contents