【问题标题】:Elixir function clauses: list of strings vs list of numbers vs tuple of strings vs tuple of numbersElixir 函数子句:字符串列表 vs 数字列表 vs 字符串元组 vs 数字元组
【发布时间】:2014-05-13 12:44:44
【问题描述】:

我想使用以下模式为 Elixir 函数指定 4 个子句: i) 字符串列表 ii) 号码列表 iii) 字符串元组 iv) 数字元组

我该怎么做?

【问题讨论】:

    标签: pattern-matching elixir


    【解决方案1】:

    大概是这样的:

    def foo([]),                      do: :empty
    def foo([h|t]) when is_binary(h), do: :list_of_strings
    def foo([h|t]) when is_number(h), do: :list_of_numbers
    def foo(tuple) when is_tuple(tuple) do
      # Convert tuple to list of stuff, then recursively call foo
      tuple |> tuple_to_list |> foo
    end
    

    最后一个子句假设您不关心从 foo 获取元组。

    【讨论】:

    • 很好地将元组转换为列表并仅使用列表函数。
    • 我还应该注意,这绝不保证整个列表/元组将是字符串或数字,您必须使用 Enum 中的一个函数来检查整个列表/tuple 如果你需要那个保证。
    • 对,它会为字符串调用 is_binary,为数字调用 is_number,如果两者都不调用,则调用 is_default。
    猜你喜欢
    • 2015-04-02
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多