【发布时间】:2020-03-21 08:20:27
【问题描述】:
Elixir 的 unquote_splicing 在直接取消引用传递的列表时可以正常工作。例如,调用Test1.wrap([1,2,3]) 下面的宏将正确返回[0,0,0,1,2,3,0,0,0]。
defmodule Test1 do
defmacro wrap(nums) do
quote do
[0,0,0, unquote_splicing(nums), 0,0,0]
end
end
end
但是如果我对列表进行任何更改然后尝试调用unquote_splicing,Elixir 甚至都不会让我定义宏:
defmodule Test2 do
defmacro double_wrap(nums) do
quote do
doubles = Enum.map(unquote(nums), & &1*2)
[0,0,0, unquote_splicing(doubles), 0,0,0]
end
end
end
这会直接引发编译错误:
warning: variable "doubles" does not exist and is being expanded to "doubles()", please use parentheses to remove the ambiguity or change the variable name
iex:37: Test.double_wrap/1
** (CompileError) iex:37: undefined function doubles/0
(elixir) src/elixir_locals.erl:108: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
(elixir) src/elixir_locals.erl:108: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
到目前为止,我已经尝试了很多东西,例如:
- 使用嵌套引号
- 使用
bind_quoted - 浏览
Macro和Code文档
但没有任何效果,我无法弄清楚我做错了什么。
【问题讨论】: