【问题标题】:Elixir - Cannot invoke remote function inside matchElixir - 无法在匹配中调用远程函数
【发布时间】:2016-02-22 10:11:04
【问题描述】:

我正在做一个关于锻炼的练习,但不知道为什么会出现以下错误:

(CompileError) anagram.exs:19: cannot invoke remote function String.codepoints/1 inside match
(stdlib) lists.erl:1353: :lists.mapfoldl/3
(stdlib) lists.erl:1353: :lists.mapfoldl/3

我想我没有像我想象的那样理解模式匹配,因为我不太明白我是如何尝试在匹配中调用远程函数的。以下是上下文测试套件的几个示例:

defmodule AnagramTest do
  use ExUnit.Case

test "no matches" do
  matches = Anagram.match "diaper", ["hello", "world", "zombies", "pants"]
  assert matches == []
end

test "detect simple anagram" do
  matches = Anagram.match "ant", ["tan", "stand", "at"]
  assert matches == ["tan"]
end

这是我的代码:

defmodule Anagram do
  @doc """
  Returns all candidates that are anagrams of, but not equal to, 'base'.
  """
  @spec match(String.t, [String.t]) :: [String.t]
  def match(base, candidates) do
    base
    |> String.codepoints
    |> Enum.sort
    |> scan_for_matches(candidates)
  end

  defp scan_for_matches(base, candidates) do
    Enum.scan candidates, [], &(if analyze(&1, base), do: &2 ++ &1)
  end

  defp analyze(candidate, base) do
    candidate
    |> String.codepoints
    |> Enum.sort
    |> match?(base)
  end

  defp match?(candidate, base) do
    candidate == base
  end
end

我不只是将变量传递给analyze/2 函数,以便它最终返回boolean吗?我很欣赏任何见解。

【问题讨论】:

  • 我认为问题出在match?/2 函数中,我没有尝试在代码中找到任何其他错误,但如果我将该函数更改为其他内容,它就会被编译。必须是保留的东西。
  • @JustMichael,就是这样。谢谢您的帮助。如果您想将其发布为答案,我会为您服务。

标签: compiler-errors pattern-matching elixir


【解决方案1】:

这确实需要一个答案,所以我想我会添加它。match?/2 是默认从Kernel 导出的函数。您可以通过 import Kernel, except: [match?: 2] 覆盖默认导入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2019-11-07
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多