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>​ [a, a] = [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 second a on the left side tries to match a 1 in the second element of the right. It doesn’t, 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 participate in the ...

Get Programming Elixir 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.