Map Pattern Matching Rules

This does not match,

`````` %{secondary: "B", first: "A"} = %{first: "A"}
``````

but this matches

``````%{first: "A"} = %{secondary: "B", first: "A"}

``````

Question is why is the second epression matching when there is only secondary: “B” on the left hand side?

Neither matches here.
Could you put it in a gist or pastebin?

3 Likes

To be honest, I don’t see a difference between those two lines, could you therefore please elaborate?

oh sorry typo please check again.

Elixir matches the values on the left hand with the values on the right hand.

Here it can find all left values on the right hand:

``````%{first: "A"} = %{secondary: "B", first: "A"}
``````

And here not:

``````%{secondary: "B", first: "A"} = %{first: "A"}
``````
2 Likes

Pattern-matching for maps passes if the keys + values on the left-hand side are present in the right. See the guide for additional discussion.

``````%{secondary: "B", first: "A"} = %{first: "A"}
``````

can’t match because the right-hand side doesn’t have `secondary` as a key.

``````%{first: "A"} = %{secondary: "B", first: "A"}
``````

can match, since the right-hand side has `first` as a key.

2 Likes

You can think of map pattern matching in the context of sets, as in whether the left-hand side of the expression (i.e. the pattern) is a subset of the right-hand side of the expression.

That’s why an ordinary map is a valid pattern for a struct, for example (provided the fields don’t mismatch of course).

1 Like

Pattern matching is leftist. Things in the left side have “more rights” than things in the right side.