Reading — step 1 of 5
Learn
~1 min readPattern Matching and Pipelines
= in Elixir isn't assignment — it's match. The left side is matched against the right.
Destructuring:
{a, b, c} = {1, 2, 3} # a=1, b=2, c=3
[head | tail] = [1, 2, 3, 4] # head=1, tail=[2,3,4]
%{name: name} = %{name: "Ada", age: 36} # name="Ada", age ignored
The pin operator ^ uses the value of an existing variable for matching:
x = 5
^x = 5 # match — true
^x = 10 # MatchError
Without ^, x = 10 would just rebind x.
Function head matching:
def handle({:ok, value}), do: value
def handle({:error, reason}), do: "failed: #{reason}"
def handle(_), do: "unknown"
The runtime tries each function head in order. First match wins. This is THE Elixir control-flow pattern.
With guards:
def classify(n) when n > 0, do: :positive
def classify(n) when n < 0, do: :negative
def classify(_), do: :zero
Guards are pure expressions evaluated in addition to the pattern. Limited set of allowed functions (no arbitrary calls).
case for in-line matching:
case parse(input) do
{:ok, value} -> use(value)
{:error, :timeout} -> retry()
{:error, reason} -> log(reason)
end
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…