Here I am trying to write a macro that generates the dynamic functions.
When I call a function times_n(3) it should generate the function as times_3(opts)
This is how I tried so far
defmodule Times do
defmacro times_n val do
name = "times_" <> to_string(val)
quote bind_quoted: [name: name,val: val] do
def(unquote(name)(n)) do
n * unquote(val)
end
end
end
end
defmodule Test do
require Times
Times.times_n(4)
Times.times_n(5)
end
It is creating function with double quotes wrapping with function name as "times_4"(n) instead of just times_4
I’m in the office right now and our firewall and router are going wild. I can’t reach half of the internet, so I have to make answers sparse.
In general there is the guides about macros on the elixir-lang.org page, this should give you some first idea about how macros work.
Another resource is available in the documentation about the Macro module.
And of course there is the book “Metaprogramming Elixir” by @chrismccord, published by pragmatic bookstore. I just started reading it, but moving slowly (still in the first chapter after 2 weeks), there is only so little time…