【问题标题】:Why doesn't this functional call match in Elixir?为什么这个函数调用在 Elixir 中不匹配?
【发布时间】:2018-04-03 23:08:21
【问题描述】:

这个函数有什么问题?

  @spec of_rna(String.t()) :: {atom, list(String.t())}
  def of_rna(rna) do
        data = rna |> String.codepoints 
                   |> Enum.chunk_every(3)
                   |> Enum.map(fn(x) -> Enum.join(x) end)
        do_rna(data, [])
  end

  def do_rna([head | tail] , Result) do
        case  @proteins[head] do
                STOP -> {:ok, Result}
                _ -> do_rna(tail, Result ++ [@proteins[head]])
        end
  end

我正在使用的测试是:

test "stops translation if stop codon present" do
    strand = "AUGUUUUAA"
    assert ProteinTranslation.of_rna(strand) == {:ok, ~w(Methionine Phenylalanine)}
  end

我看到的错误是:

1) test stops translation if stop codon present (ProteinTranslationTest)
     protein_translation_test.exs:67
     ** (FunctionClauseError) no function clause matching in ProteinTranslation.do_rna/2

     The following arguments were given to ProteinTranslation.do_rna/2:

         # 1
         ["AUG", "UUU", "UAA"]

         # 2
         []

     code: assert ProteinTranslation.of_rna(strand) == {:ok, ~w(Methionine Phenylalanine)}
     stacktrace:
       protein_translation.exs:37: ProteinTranslation.do_rna/2
       protein_translation_test.exs:69: (test)

我不明白为什么函数调用不匹配。请帮忙。

【问题讨论】:

  • elixir 中的变量是小写的。你在do_rna/2 的第二个参数中有Result。那是 Elixir 中的一个原子。

标签: pattern-matching elixir


【解决方案1】:

您可能打算在do_rna 中写result 而不是Result。以大写字母开头的标识符是 Elixir 中的一个原子。对于Result,只有当第二个值是Result:"Elixir.Result" 时,该子句才会匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2023-01-08
    • 1970-01-01
    • 2014-11-18
    相关资源
    最近更新 更多