简体   繁体   English

Elixir:如何使用List作为变量定义多个宏?

[英]Elixir: How to define multiple macros using a List as a variable?

I'm trying to define two macros with the following code but it failed with ** (CompileError) iex:12: undefined function name/0 . 我正在尝试使用以下代码定义两个宏但它失败了** (CompileError) iex:12: undefined function name/0 The function parameter name cannot be unquoted in the do block of defmacro . 函数参数name不能在defmacro的do块中defmacro

What is the reason of this ? 这是什么原因? Is there any way to solve this? 有什么方法可以解决这个问题吗?

(Elixir version is 1.2.5) (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

You basically need to unquote twice, since the dynamic macro generation already is an implicit macro. 您基本上需要取消引用两次,因为动态宏生成已经是隐式宏。 You should be fine with adding the following line at the top of your defmacro : 你可以在你的defmacro顶部添加以下行:

name = unquote(name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM