I am learning Elixir from offical docs.
I am bit confused about my comprehension of Elixir's pattern matching. Please have a look at below example.
[_] = [1,2,3]
gives
(MatchError) no match of right hand side value: [1, 2, 3]
(stdlib 5.0.2) erl_eval.erl:498: :erl_eval.expr/6
iex:32: (file)
But why doesnt below code produce such error. I feel like I am missing something.
%{name: person_name} = %{name: "Fred", favorite_color: "Taupe"}
gives
%{name: "Fred", favorite_color: "Taupe"}
I did nothing much. I asked chatgpt.
Lists in elixir are linked lists, which means there is no instant access to the n-th element, unlike arrays in many other languages.
Tuples in elixir are lists of fixed length, with instant access to the n-th element, like fixed length arrays in many other languages.
Maps in elixir are, well, maps, with instant access to the named element, as in many other languages.
That said, to match the above, one needs:
[one | _tail] = [1, 2, 3]
, or [first_elem, _, _] = [1, 2, 3]
(the latter implicitly defines the exact shape of a list, which is its length){_, two, _} = {1, 2, 3}
%{third_elem: three} = %{first_elem: 1, second_elem: 2, third_elem: 3}