How to create a dynamic function name using Elixir macro?

前端 未结 3 1027
忘掉有多难
忘掉有多难 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:36

    I did this same sort of thing in a gist to try and mimic Ruby's attr_accessor:

    defmodule MacroExp do
      defmacro attr_accessor(atom) do
        getter = String.to_atom("get_#{atom}")
        setter = String.to_atom("set_#{atom}")
        quote do
          def unquote(getter)(data) do
            data |> Map.from_struct |> Map.get(unquote(atom))
          end
          def unquote(setter)(data, value) do
            data |> Map.put(unquote(atom), value)
          end
        end
      end
    
      defmacro attr_reader(atom) do
        getter = String.to_atom("get_#{atom}")
        quote do
          def unquote(getter)(data) do
            data |> Map.from_struct |> Map.get(unquote(atom))
          end
        end
      end
    end
    
    
    defmodule Calculation do
      import MacroExp
      defstruct first: nil, second: nil, operator: :plus
    
      attr_accessor :first   # defines set_first/2 and get_first/1
      attr_accessor :second  # defines set_second/2 and get_second/1
      attr_reader :operator  # defines set_operator/2 and get_operator/1
    
      def result(%Calculation{first: first, second: second, operator: :plus}) do
        first + second
      end
    end
    

    https://gist.github.com/rcdilorenzo/77d7a29737de39f0cd84

提交回复
热议问题