【问题标题】:Elixir: pattern matching multiple lists in function signatureElixir:模式匹配函数签名中的多个列表
【发布时间】:2018-11-24 16:16:59
【问题描述】:

我正在尝试创建一个函数,该函数接受两个列表作为参数,并且每个列表 (a) 不为空,并且 (b) 是某个结构的列表。像这样的东西可以满足我的需要:

def zip_sports_and_leagues(
  [%Sport{} | _tail] = sports,
  [%League{} | _tail] = leagues
) do
  # Do stuff with `sports` and `leagues`
end

当第一个列表有多个项目时,该函数出现“无函数子句匹配”错误。

我已将代码精简为这个最小的示例:

defmodule Test do
  def test([a | _tail], [b | _tail]) do
    1
  end
end

Test.test([1], [1])
=> 1

Test.test([1, 1], [1])
** (FunctionClauseError) no function clause matching in Test.test/2

    The following arguments were given to Test.test/2:

        # 1
        [1, 1]

        # 2
        [1]

谁能告诉我为什么会出现函数子句错误以及如何修复它?

谢谢!

【问题讨论】:

    标签: elixir


    【解决方案1】:

    问题是您对两个参数的尾部使用了相同的名称:_tail。当函数参数中的名称被使用两次时,子句仅在两者具有相同值时匹配。您可以重命名其中一个:

    def zip_sports_and_leagues(
      [%Sport{} | _tail] = sports,
      [%League{} | _tail2] = leagues
    ) do
      # Do stuff with `sports` and `leagues`
    end
    

    或者使用_不绑定值,可以多次使用:

    def zip_sports_and_leagues(
      [%Sport{} | _] = sports,
      [%League{} | _] = leagues
    ) do
      # Do stuff with `sports` and `leagues`
    end
    

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多