How can I use Kernel.apply for macro function

The Kenel.apply / 3 function from the elixir could not call the function that is defined by the macro.

Example,

defmodule Hoge1 do
  for fun_name <- [:foo, :bar] do
    defmacro unquote(fun_name)(arg) do
      apply(Hoge2, unquote(fun_name), [arg])
    end
  end
end

defmodule Hoge2 do
  for fun_name <- [:foo, :bar] do
    defmacro unquote(fun_name)(arg) do
      IO.puts "hoge2"
    end
  end
end

above, if I call Hoge1.foo, the error goes up. ( undefined function: Hoge2.foo/1)

I can directly call Hoge2.foo/1. (He displays "hoge2")

Can I call using Kernel.apply / 3?

+4
source share
1 answer

applywill only work with functions, not macros. First you need to check if you really need macros, because many problems can (and should) be solved only with the help of functions. In this case, you can simply use definstead defmacro:

defmodule Hoge1 do
  for fun_name <- [:foo, :bar] do
    def unquote(fun_name)(arg) do
      apply(Hoge2, unquote(fun_name), [arg])
    end
  end
end

defmodule Hoge2 do
  for fun_name <- [:foo, :bar] do
    def unquote(fun_name)(arg) do
      IO.puts "hoge2"
    end
  end
end

, , apply:

Hoge2.unquote(fun_name)(arg)

Hoge2 Hoge1, Hoge2 Hoge1. :

defmodule Hoge2 do
  for fun_name <- [:foo, :bar] do
    defmacro unquote(fun_name)(arg) do
      IO.puts "hoge2"
    end
  end
end

defmodule Hoge1 do
  require Hoge2

  for fun_name <- [:foo, :bar] do
    defmacro unquote(fun_name)(arg) do
      Hoge2.unquote(fun_name)(arg)
    end
  end
end
+2

Source: https://habr.com/ru/post/1614589/


All Articles