Pattern matching literals vs bounded variables

I just discovered this:

match?(%{a: 1}, %{a: 1, b: 2}) # true  

the_match = %{a: 1}
match?(^the_match, %{a: 1, b: 2}) # false

weird. But makes sense, because probably a ^thing is an exact match.

Given that I receive the pattern to be matched in a variable, do you think that there is a way to have the normal pattern matching behavior?

Many thanks!

1 Like

found this solution which says:

  1. it’s impossible
  2. there is a workaround if the context is 2 maps with one level of nesting.

Probably there isn’t a solution for arbitrary pattern matching :frowning:

1 Like

But why does it need to be pinned?

iex(1)> the_match = %{a: 1}
%{a: 1}
iex(2)> match?(the_match, %{a: 1, b: 2})
true

Edit: Ah I see the same problem occurred in the other thread and it’s only matching it as a map, not checking if it’s a subset.

Failing that and with a receive, you might try creating a match spec dynamically. Combined with :erlang.trace_pattern/[2,3] you might be able to accomplish your goal.

Edit:

I’ve found that this works:

k = :a 
v = 1
match?(%{^k => ^v}, %{a: 1, b: 2})
true
v = 9
match?(%{^k => ^v}, %{a: 1, b: 2})
false
2 Likes