How to create a dynamic function name using Elixir macro?

前端 未结 3 1026
忘掉有多难
忘掉有多难 2020-12-30 19:12

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         


        
3条回答
  •  北海茫月
    2020-12-30 19:41

    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"
    

提交回复
热议问题