Skip to content
Elixir

Pattern Matching

Pattern matching is core to Elixir — used everywhere.

By EZ4Code Team
pattern-matchingmatch

Code

# = is a match operator, not assignment
{:ok, value} = {:ok, 42}
IO.puts(value)  # 42

# Works with lists
[head | tail] = [1, 2, 3]
IO.puts(head)        # 1
IO.inspect(tail)     # [2, 3]

# Maps
%{name: name} = %{name: "Alice", age: 30}
IO.puts(name)  # "Alice"

# Function heads with multiple clauses
defmodule Math do
  def factorial(0), do: 1
  def factorial(n) when n > 0, do: n * factorial(n - 1)
end

# Case expression
case File.read("config.txt") do
  {:ok, contents} -> IO.puts("Loaded: #{contents}")
  {:error, :enoent} -> IO.puts("File not found")
  {:error, reason} -> IO.puts("Error: #{reason}")
end

# Pin operator (^) — match against existing value
x = 10
^x = 10   # matches
# ^x = 20  # MatchError!

Explanation

= is a match operator — it asserts both sides are equal and binds variables on the left. Multiple function clauses are tried in order; the first matching one wins. Guards (when) refine matches. The pin operator (^) forces a comparison against an existing value rather than rebinding. Pattern matching powers Elixir's control flow.

More Elixir Snippets