I’m not looking for an answer for what I’m trying to do. Instead, I want to know why I’m getting an error.
I’m trying to return a def from a macro, but I want to change the name of the def in the code tuple before returning the code tuple from the macro–but I’m getting an error. Here’s my code:
defmodule My do
defmacro times_n(n) do
quote do
def times(x) do
x * unquote(n)
end
end
|> IO.inspect
|> replace_func_name(n)
|> IO.inspect
end
def replace_func_name(
{
:def,
context,
[
{func_name, context_import, x},
sublist
]
},
n
) do
{
:def,
context,
[
{:"#{func_name}_#{n}", context_import, x},
sublist
]
}
end
end
defmodule Test do
require My
My.times_n(5)
end
IO.puts My.times_5(3)
Here’s the output I see:
~/elixir_programs$ iex macros2.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
{:def, [context: My, import: Kernel],
[
{:times, [context: My], [{:x, [], My}]},
[do: {:*, [context: My, import: Kernel], [{:x, [], My}, 5]}]
]}
{:def, [context: My, import: Kernel],
[
{:times_5, [context: My], [{:x, [], My}]},
[do: {:*, [context: My, import: Kernel], [{:x, [], My}, 5]}]
]}
** (UndefinedFunctionError) function My.times_5/1 is undefined or private. Did you mean one of:
* times_n/1
My.times_5(3)
macros2.ex:39: (file)
(elixir) lib/code.ex:677: Code.require_file/2
It looks like I’ve correctly changed the name of the function in the code tuple, but I still get the undefined function error for My.times_5()
. Can someone tell me why that is?