Pattern matching in Elixir

Can you help me understand why Elixir works this way?

For example:

iex(1)> a=[[1,2,3]]
[[1, 2, 3]]
iex(2)> [a]=[[1,2,3]]
[[1, 2, 3]]
iex(3)> [[a]]=[[1,2,3]]
** (MatchError) no match of right hand side value: [[1, 2, 3]]

Why do you get a match error on iex(3) but not on iex(2)?

I am not very good at explaining.

[a]=[[1,2,3]]
a = [1,2,3]

[[a,b,c]]=[[1,2,3]]
a=1
b=2
c=3

The value returned to the terminal in the second try is the whole expression not of ‘a’, if I understand correctly the second makes ‘a’ equal to [1, 2, 3] while the third one tries match a list of one element [a] on the left to a list of 3 elements on the right, which can’t be matched with that syntax as they don’t have the same number of elements

1 Like

This helped me see it. Thank you.

1 Like