🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Pattern Matching

Pattern matching is a check that a value fits a pattern, binding variables where the pattern has names. The pin operator and the underscore give that check two useful twists.

A literal on the left must match

A number on the left side does not bind anything. The match succeeds only when the right side holds that same value.

score = 42
42 = score
IO.inspect(score)

A variable on the left rebinds

A variable on the left side takes the value on the right side. Writing the same variable again with a new value rebinds it.

status = :ok
IO.inspect(status)
status = :done
IO.inspect(status)

The pin matches the current value

The ^ operator pins a variable to the value it already holds. The match then checks that value instead of rebinding the variable.

expected = 7
answer = 7
^expected = answer
IO.inspect(expected)
IO.inspect(answer)

The underscore ignores a value

The _ name matches any value and keeps nothing. It can accept a number and then a string in the same script.

_ = 10
_ = "hello"
result = 3
IO.inspect(result)

Example

limit = 100
_ = 500
score = 100
100 = score
^limit = score
IO.inspect(score)
IO.inspect(limit)

Key points

  • Match operator: The = sign checks that the left side matches the right side.
  • Binding: A fresh variable on the left side binds to the value on the right side.
  • Literal match: A number or atom on the left side must equal the value on the right side.
  • Pin operator: The ^ sign matches a variable against its current value instead of rebinding it.
  • Underscore: The _ name matches any value and ignores it.
  • Failed match: A match that does not fit raises a MatchError and stops the script.

In this example, the underscore ignores the value 500, and the score binds to 100. The literal 100 then matches the score, and the pinned limit matches because it already holds 100. The last two lines print the score and the limit.

Note

In many other languages = only assigns a value, while in Elixir it always performs a match.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

With x = 5 already bound, what does the match ^x = 5 do?