如何在保护子句中使用'in'运算符?

问题描述 投票:12回答:1

我正在尝试用Elixir写一个字谜检查器。它需要2个字,第一个是参考,第二个将作为第一个可能的字谜进行测试。

我正在尝试使用递归和模式匹配来编写它。我在保护子句中使用in运算符时遇到错误:

((ArgumentError)无效的args用于运算符,它需要编译在保护表达式中使用的时间列表或范围在右侧

我不知道该如何解决。这是代码(错误在第4个定义中):

defmodule MyAnagram do
  def anagram?([], []), do: true

  def anagram?([], word) do
    IO.puts 'Not an anagram, the reference word does not contain enough letters'
    false
  end

  def anagram?(reference, []) do
    IO.puts 'Not an anagram, some letters remain in the reference word'
    false
  end

  def anagram?(reference, [head | tail]) when head in reference do
    anagram?(reference - head, tail)
  end

  def anagram?(_, [head | _]) do
    IO.puts 'Not an anagram, #{head} is not in the reference word.'
    false
  end
end
pattern-matching elixir anagram
1个回答
18
投票

这是由以下代码(您所确定的)引起的:

def anagram?(reference, [head | tail]) when head in reference do
  anagram?(reference - head, tail)
end

您可以找到inin the source code的定义,但是为了方便起见,在这里已将其复制-在文档中还包含以下内容:

守卫

in运算符可以在保护子句中使用,只要因为右侧是范围或列表。在这种情况下,长生不老药将运算符扩展为有效的保护表达式。例如:

  when x in [1, 2, 3] 

翻译为:

  when x === 1 or x === 2 or x === 3

定义宏的代码:

  defmacro left in right do
    in_module? = (__CALLER__.context == nil)

    right = case bootstraped?(Macro) and not in_module? do
      true  -> Macro.expand(right, __CALLER__)
      false -> right
    end

    case right do
      _ when in_module? ->
        quote do: Elixir.Enum.member?(unquote(right), unquote(left))
      [] ->
        false
      [h|t] ->
        :lists.foldr(fn x, acc ->
          quote do
            unquote(comp(left, x)) or unquote(acc)
          end
        end, comp(left, h), t)
      {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} ->
        in_range(left, Macro.expand(first, __CALLER__), Macro.expand(last, __CALLER__))
      _ ->
        raise ArgumentError, <<"invalid args for operator in, it expects a compile time list ",
                                        "or range on the right side when used in guard expressions, got: ",
                                        Macro.to_string(right) :: binary>>
    end
  end

您的代码块到达了case语句的最后一部分,因为不能在编译时保证变量reference的类型为list(或range。]

您可以通过调用查看正在传递给宏的值:

iex(2)> quote do: head in reference                                       
{:in, [context: Elixir, import: Kernel],
 [{:head, [], Elixir}, {:reference, [], Elixir}]}

[这里,原子:reference被传递到in宏,该宏与前面的任何子句都不匹配,因此它属于_子句(这会引起错误。)

要解决此问题,您需要将最后两个子句合并为一个函数:

  def anagram?(reference, [head | tail]) do
    case head in reference do
      false ->
        IO.puts 'Not an anagram, #{head} is not in the reference word.'
        false
      true ->
        anagram?(reference - head, tail)
    end
  end

同样值得注意的是,您可能想使用"strings"而不是'char_lists' http://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#char-lists

另一件事是,调用reference - head将不起作用(它将引发ArithmeticError)。您可能要查看List.delete/2从列表中删除一个项目。

© www.soinside.com 2019 - 2024. All rights reserved.