Macro for Creating Dynamic Function Bodies

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)

defmodule Test do
  require Times

It is creating function with double quotes wrapping with function name as "times_4"(n) instead of just times_4

Screen Shot of error

Am I missing anything here?
Thanks in advance :bouquet:

1 Like

Function names need to be atoms, so after plunbing the string together, you need to convert it to an atom.


Thanks for the quick reply :tada: :tada:

1 Like

Can you suggest me where can I read more stuff about the macros in more detail. :smile:

1 Like

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 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…

1 Like

Thanks for Everything… :bouquet: :bouquet: