应该将元组传递给宏吗?

Fen*_*eng 3 elixir

处理元组的方式似乎不一致:

defmodule A do
  defmacro a(x) do
    IO.inspect x
    quote do end
  end
end
Run Code Online (Sandbox Code Playgroud)

A.a {:a, :b}版画{:a, :b}不如预期,但A.a {:a}打印{:{}, [line: 2], [:a]}

Dog*_*ert 5

宏接收他们的参数作为引用的表达式,在Elixir中,长度为2的元组表示为自己,其余的表示为{:{}, _, [value1, value2, ...]}:

iex(1)> Macro.escape {}
{:{}, [], []}
iex(2)> Macro.escape {1}
{:{}, [], [1]}
iex(3)> Macro.escape {1, 2}
{1, 2}
iex(4)> Macro.escape {1, 2, 3}
{:{}, [], [1, 2, 3]}
iex(5)> Macro.escape {1, 2, 3, 4}
{:{}, [], [1, 2, 3, 4]}
Run Code Online (Sandbox Code Playgroud)

如果将这些值注入到quoteusing中unquote,它们将自动转换为实际元组.我们可以看到使用Macro.to_string/2:

iex(6)> Macro.to_string {:{}, [], [1, 2, 3]}
"{1, 2, 3}"
Run Code Online (Sandbox Code Playgroud)

您可以在Quote和unquote - > Escaping入门指南中找到有关此内容的更多信息.