针对空图的模式匹配功能 [英] Pattern match function against empty map
问题描述
我正在研究模式匹配,但我发现,针对空地图对方法的参数进行模式匹配并不容易。我认为应该是这样的:
I'm playing around with pattern match and I found out, that it's not quite easy to pattern match parameters of a method against an empty map. I thought it would go something like this:
defmodule PatternMatch do
def modify(%{}) do
%{}
end
def modify(map) do
# expensive operation
%{ modified: "map" }
end
end
但似乎第一个函数子句匹配任意映射:
But it seems like the first function clause matches arbitrary maps:
iex> PatternMatch.modify(%{a: "map"})
==> %{}
还有另一种检查空地图的方法吗?
Is there another way to check for empty maps?
推荐答案
这种方式在设计上是可行的,但是乍一看,它可能会有些混乱。此功能使您可以使用模式匹配来解构地图,而不必指定所有键。例如:
It works this way by design, but admittedly it can be a bit confusing at first glance. This feature allows you to destructure maps using pattern matching, without having to specify all keys. For example:
iex> %{b: value} = %{a: 1, b: 2, c: 3}
%{a: 1, b: 2, c: 3}
iex> value
2
因此,%{}
将匹配任何地图。如果要匹配函数中的空映射,则必须使用保护子句:
Consequently, %{}
will match any map. If you want to match an empty map in a function, you have to use a guard clause:
defmodule PatternMatch do
def modify(map) when map == %{} do
%{}
end
def modify(map) do
# ...
end
end
这篇关于针对空图的模式匹配功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!