【问题标题】:Regex and Map argument matching正则表达式和 Map 参数匹配
【发布时间】:2016-09-12 10:39:25
【问题描述】:

在编写函数时,我使用的是这样的参数匹配:

def process_thing( %{} = thing )

我期待thing 是一个映射,并且是可枚举的。不幸的是,这个参数列表也匹配指定为~r/regex/ 的正则表达式,并且正则表达式(尽管它为is_map(~r/thing/) 返回真)不是可枚举的。

我怎样才能制作这个函数定义,以便只有 Maps - 或者理想情况下是 Enumerable 的东西 - 被分派给这个函数?

【问题讨论】:

    标签: regex dictionary elixir enumerable


    【解决方案1】:

    没有办法匹配 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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2013-09-22
      相关资源
      最近更新 更多