I want to create a function names dynamically. I wrote this macro
defmacro generate_dynamic(name) do
quote do
def add_(unquote(name)) do
end
end
Sometimes, as a useful shortcut, you can achieve the same result inline, without writing a macro using an unquote fragment.
defmodule Hello do
[:alice, :bob] |> Enum.each fn name ->
def unquote(:"hello_#{name}")() do
IO.inspect("Hello #{unquote(name)}")
end
end
end
Hello.hello_bob # => "Hello bob"
Hello.hello_alice # => "Hello alice"