@@ -129,14 +129,33 @@ iex> x = 1
129129iex> x = 2
1301302
131131```
132+ However, there are times when we don't want variables to be rebound.
132133
133- Use the pin operator ` ^ ` when you want to pattern match against an existing variable's value rather than rebinding the variable:
134+ Use the pin operator ` ^ ` when you want to pattern match against a variable's _ existing value _ rather than rebinding the variable.
134135
135136``` iex
136137iex> x = 1
1371381
138139iex> ^x = 2
139140** (MatchError) no match of right hand side value: 2
141+ ```
142+
143+ Because we have pinned ` x ` when it was bound to the value of ` 1 ` , it is equivalent to the following:
144+
145+ ``` iex
146+ iex> 1 = 2
147+ ** (MatchError) no match of right hand side value: 2
148+ ```
149+
150+ Notice that we even see the exact same error message.
151+
152+ We can use the pin operator inside other pattern matches, such as tuples or lists:
153+
154+ ``` iex
155+ iex> x = 1
156+ 1
157+ iex> [^x, 2, 3] = [1, 2, 3]
158+ [1, 2, 3]
140159iex>{y, ^x} ={2, 1}
141160{2, 1}
142161iex> y
@@ -145,13 +164,26 @@ iex>{y, ^x} ={2, 2}
145164** (MatchError) no match of right hand side value:{2, 2}
146165```
147166
148- Because we have assigned the value of 1 to the variable x , this last example could also have been written as:
167+ Because ` x ` was bound to the value of ` 1 ` when it was pinned , this last example could have been written as:
149168
150- ```
169+ ``` iex
151170iex>{y, 1} ={2, 2}
152171** (MatchError) no match of right hand side value:{2, 2}
153172```
154173
174+ When using the pin operator in maps you must use the ` => ` syntax when pinning a map's key, even when the value being pinned is an atom:
175+
176+ ``` iex
177+ iex> k = :foo
178+ :foo
179+ iex> %{^k: v} = %{foo: "bar"}
180+ ** (SyntaxError) iex:11: syntax error before: k
181+ iex> %{^k => v} = %{foo: "bar"}
182+ %{foo: "bar"}
183+ iex> v
184+ "bar"
185+ ```
186+
155187If a variable is mentioned more than once in a pattern, all references should bind to the same pattern:
156188
157189``` iex
0 commit comments