为什么match?
在所需模式存储在变量中时会停止匹配?即:
iex> match?(%{a: 1}, %{a: 1}) # true
iex> match?(%{a: 1}, %{a: 1, b: 2}) # true
iex> pattern = %{a: 1}
iex> match?(^pattern, %{a: 1}) # true
iex> match?(^pattern, %{a: 1, b: 2}) # false, why?
请注意在^
的第一个参数中使用pin operator match?
。
经过进一步测试后,我注意到matching operator =
的行为相同,如下所示:
iex> ^pattern = %{a: 1}
%{a: 1}
iex> ^pattern = %{a: 1, b: 2}
** (MatchError) no match of right hand side value: %{a: 1, b: 2}
编辑:
阅读match?
文档后,我无法找到有关此行为的信息。
答案 0 :(得分:1)
[Pin operator]访问match子句中已绑定的变量。也称为销操作员。
-Kernel.SpecialForms.^/1
那就是说,你的例子中pattern
不仅仅是匹配的参数,它是一个绑定变量,具有它的值。
Pin操作符不会引入任何魔法,它只是将所有内容传递给Erlang。在Erlang中:
V1 = #{foo => 42},
V2 = #{foo => 42, bar => baz},
V1 = V2.
%%⇒ ** exception error: no match of right hand side
%% value #{bar => baz,foo => 42}
虽然这种行为似乎没有预期/自然/与模式匹配就地术语一致,但这是Erlang处理它的方式,并且没有责任归咎于Elixir,这不会带来额外的初步处理。
但是Elixir邮件列表可能是一个很好的问题;因为与Erlang不同,Elixir具有这种可变的反弹,它可能会在这里向更直观的处理迈出新的一步。