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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With