trisolaran

trisolaran

Thanks @LostKobrakai that’s the best answer I’ve seen to this question so far.

So the reason why this works:

iex(2)> one = 1
1
iex(3)> %{a: ^one} = %{a: 1, b: 2}
%{a: 1, b: 2}

But this one doesn’t:

iex(1)> map_with_one = %{a: 1}
%{a: 1}
iex(2)> ^map_with_one = %{a: 1, b: 2}
** (MatchError) no match of right hand side value: %{a: 1, b: 2}

Is because the pin operator can only be used for exact matches but not for partial ones, the reason being intrinsic limitations of the BEAM. Correct?

0
Post #11
LostKobrakai

LostKobrakai

Yes, but I’d suggest not even trying to think of it like that. There’s (runtime) data assigned to a variable like map_with_one and there’s syntax, which can in some cases look exactly like the syntax used to define the data for map_with_one, but which forms a pattern for a pattern match. One is completely unrelated to the other. This becomes even more apparent when you consider the features of a match pattern, which a map of data doesn’t support, like _ for ignoring values or variable assignments %{a: a} = ….

The pin operator is a way to use data assigned to a variable to be equality matched within a pattern. Nothing more and nothing less. It does not become a pattern by itself. Patterns are compile time structures, which cannot be adjusted at runtime, stored in a variable or otherwise modified after compilation is done. Only patterns can be used for a pattern match on the left side of the match operator (=). When you put a variable on the left side it’s either an assignment, or if you use a pin an equality check to match the pattern.

11
Post #12
trisolaran

trisolaran

Thanks! Excellent explanation :+1:

0
Post #13
— All posts loaded —