Elixir The Pin Operator
In a pattern, a variable name normally means "bind whatever is here". Sometimes you want the opposite: "this position must equal the value I already have in this variable". That is what the pin operator ^ does.
Rebinding versus pinning
expected = :ok
IO.inspect(expected)
expected = :error # plain variable: rebinds, always succeeds
IO.inspect(expected)
expected = :ok
try do
^expected = :error # pinned: must equal :ok, so it fails
rescue
e in MatchError -> IO.puts(Exception.message(e))
end:ok
:error
no match of right hand side value:
:error
Think of ^x as "the current value of x, used as a literal".
Pinning inside larger patterns
Pins are most useful inside tuples, lists and maps, when part of a value must match something you already know:
order_id = 42
messages = [
{:shipped, 41, "Paris"},
{:shipped, 42, "Nairobi"},
{:cancelled, 42, nil}
]
for {:shipped, ^order_id, city} <- messages do
IO.puts("Order #{order_id} was shipped to #{city}")
endOrder 42 was shipped to Nairobi
In a for comprehension, elements that don't match the pattern are skipped, so only the message for order 42 with the :shipped tag is printed.
Pins in case
Without the pin, the variable in a case clause would simply be rebound and the first clause would always match. This is a classic beginner bug:
target = 7
check = fn guess ->
case guess do
^target -> "correct!"
n when n < target -> "#{n} is too low"
n -> "#{n} is too high"
end
end
IO.puts(check.(3))
IO.puts(check.(7))
IO.puts(check.(9))3 is too low
correct!
9 is too high
If you wrote target -> "correct!" instead of ^target ->, every guess would be "correct!", because target would bind to whatever guess is. The compiler helps here: it warns that the outer target is unused or shadowed.
Pinning map keys and repeated variables
You can pin a value used as a map key in a pattern (keys in patterns must be literals or pinned variables):
key = "es"
translations = %{"en" => "hello", "es" => "hola", "fr" => "bonjour"}
%{^key => word} = translations
IO.puts(word)
# The same variable twice in one pattern means "these must be equal"
{x, x} = {5, 5}
IO.puts("both are #{x}")
try do
{y, y} = {5, 6}
IO.inspect(y)
rescue
e in MatchError -> IO.puts(Exception.message(e))
endhola
both are 5
no match of right hand side value:
{5, 6}
Tip: A pinned variable must already be bound.
^undefined_name = 1is a compile error.
When you need it
| Situation | Use |
|---|---|
| Extract a value from data | plain variable x |
| Check data against a value you have | pin ^x |
| A key in a map pattern from a variable | %{^key => value} |
Messages for a specific request (receive) |
{^ref, reply} |
The last row comes back in the Processes lesson: when you send a request with a unique reference, you match the reply with {^ref, reply} so that you only receive the answer to your request.
Test yourself
With x = 1, what does ^x = 2 do?
- Rebinds x to 2
- Raises a MatchError
- Returns false
- Compiles to x == 2
Why does a case clause target -> ... (without a pin) match every value?
- Because case clauses ignore variables
- Because a plain variable in a pattern binds to anything
- Because target is nil
- It doesn't; it raises
Does {x, x} = {3, 3} succeed?
- Yes, and x is 3
- No, a variable can only appear once
- Yes, and x is {3, 3}
- No, it raises CompileError