Variables Bind Once (per Match)
Once a variable has been bound to a value in the matching process, it keeps that value for the remainder of the match.
| iex> [a, a] = [1, 1] |
| [1, 1] |
| iex> a |
| 1 |
| iex> [b, b] = [1, 2] |
| ** (MatchError) no match of right hand side value: [1, 2] |
The first expression in this example succeeds because a is initially matched with the first 1 on the right side. The value in a is then used in the second term to match the second 1 on the right side.
In the next expression, the first b matches the 1. But the second b corresponds to the value 2 on the right. b cannot have two different values, and so the match fails.
However, a variable can be bound to a new value in a subsequent match, and its current value does not ...
Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.