没有办法匹配 Enumerable。如果你只用地图没问题,那么你有 is_map/1 内置函数:
def process_thing(thing) when is_map(thing) do
...
end
另一种方法是检查您期望和支持的所有数据类型:
def process_thing(thing) when is_map(thing) or is_list(thing), do: ...
def process_thing(%MapSet{}), do: ...
...
如果你需要支持所有个枚举(也许提供更多关于你的用例的信息会更容易),你总是可以使用Protocol.assert_impl!/2:
def process_thing(thing) when is_map(thing) or is_list(thing), do: ...
def process_thing(%{__struct__: struct}) do
assert_impl!(Enumerable, struct)
end
并处理Protocol.assert_impl!/2 可能出现的故障。我不确定这个实现是否是防弹的,同样,可能有一种更清洁的方法来实现它。 :)
还有一件事:如果你想匹配地图但不匹配结构(如Regex),解决它的一种方法是首先匹配你不想要的东西匹配,以便您将它们排除在外(并根据需要处理它们):
def process_thing(%{__struct__: _}), do: # bad things here, we don't like structs
def process_thing(%{} = thing), do: # hey, that's a map now!