【问题标题】:Elixir: How to define multiple macros using a List as a variable?Elixir:如何使用 List 作为变量来定义多个宏?
【发布时间】:2016-05-15 18:12:15
【问题描述】:

我正在尝试使用以下代码定义两个宏,但使用 ** (CompileError) iex:12: undefined function name/0 失败。 函数参数name 不能在defmacro 的do 块中不加引号。

这是什么原因? 有没有办法解决这个问题?

(Elixir 版本为 1.2.5)

defmodule IEx.MyHelpers do

  def default_env do
    __ENV__
  end

  [:functions, :macros] |> Enum.each(fn name ->
    defmacro unquote(name)(option \\ :all) do
      import MapSet
      quote do
        case unquote(option) do
          x when x in [:a, :all]      -> __ENV__     |> Map.take([unquote(name)])
          x when x in [:d, :default]  -> default_env |> Map.take([unquote(name)])
          x when x in [:i, :imported] ->
            difference(new(Map.take(__ENV__, [unquote(name)])),
                       new(Map.take(default_env, [unquote(name)])))
            |> MapSet.to_list
        end
      end
    end
  end)

end

【问题讨论】:

    标签: macros elixir


    【解决方案1】:

    你基本上需要取消引用两次,因为动态宏生成已经是一个隐式宏。您应该可以在 defmacro 的顶部添加以下行:

    name = unquote(name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2018-02-10
      • 2016-01-08
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多