Search code examples
elixir

Why there is no match error when matching Maps in Elixir


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.


Solution

  • Lists in are linked lists, which means there is no instant access to the n-th element, unlike arrays in many other languages.

    Tuples in are lists of fixed length, with instant access to the n-th element, like fixed length arrays in many other languages.

    Maps in are, well, maps, with instant access to the named element, as in many other languages.


    That said, to match the above, one needs:

    • list → specify a structure, as in [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)
    • tuple → specify the length and the exact position, as in {_, two, _} = {1, 2, 3}
    • map → specify the name of the element to match, aka key, as in %{third_elem: three} = %{first_elem: 1, second_elem: 2, third_elem: 3}