Reputation: 662
I am new to Elixir so I am little confused with these three statements
a = [ [ 1, 2, 3 ] ]
[a] = [ [ 1, 2, 3 ] ]
[[a]] = [ [ 1, 2, 3 ] ]
The first and second statements return result as expected but the third one throws a error
** (MatchError) no match of right hand side value: [[1, 2, 3]]
I want to know why the third sentence threw an error
Upvotes: 2
Views: 1216
Reputation: 120990
While the answer by @Dogbert explains why it did not work for the latter case, here are examples of how it would work:
iex|1 ▶ [[a, _, _]] = [ [ 1, 2, 3 ] ]
#⇒ [[1, 2, 3]]
iex|2 ▶ [[^a, 2, 3]] = [ [ 1, 2, 3 ] ]
#⇒ [[1, 2, 3]]
iex|3 ▶ a
#⇒ 1
Also note a Kernel.SpecialForms.^/1
pin operator in line 2: it basically enforces the already bound variable a
to be matched not rebound.
Upvotes: 2
Reputation: 15293
To amplify this even a bit further consider:
a = [[1,2,3]]
# a is [[1,2,3]]
[ a ] = [ [1,2,3] ]
^ ^ ^ ^ These match.
#a is [1,2,3]
[ [ a ] ] = [ [ 1,2,3 ] ]
^ ^ ^ ^ ^ ^ ^ ^ These match as well.
# You can consider that the parts that match on the left and the right of
# the pattern match operator are effectively discarded and then elixir attempts to assign
# the remaining portion on the right side to the remaining portion on the left side.
# Hence on the last expression it's trying to assign 1,2,3 to a. The pattern doesn't match
# because you have three values on the right but only one name on the left to bind to.
I hope that may help clarify the situation. @Dogbert and @mudasobwa are both completely correct; I just hope this helps to make the situation a little clearer.
Upvotes: 2
Reputation: 222040
a
matches any value. [a]
matches a list containing exactly one element which can be any value. [[a]]
matches a list of exactly one element containing another list of exactly one element which can be any value.
The expression [[1, 2, 3]]
matches the first two patterns but doesn't match the third because it's a list of one list containing three elements.
Upvotes: 10