How to create a dynamic function name using Elixir macro?

To achieve this, you can prepend :add_ to the name before unquoting. Also, the parentheses after the method name in this case are required to prevent ambiguities. This should do the trick:

defmacro generate_dynamic(name) do
  quote do 
    def unquote(:"add_#{name}")() do
      # ...
    end
  end
end

Leave a Comment