Generating for loops with macros

I am having difficulty trying to write a macro that takes a vector of types, defines 3 input parameters for the constructor of each type, loops over different values of the parameters and instantiates the types inside of the loop. Consider this pseudo-code:

using Plots, Interact

macro loop_ctor(types)
  quote
    for i=1:length($types)
      # define variables ai, bi, ci for the ith type
    end
    # write a for loop with all variables defined above
    @manipulate for a1=1:10, b1=1:10, c1=1:10, a2=1:10, b2=1:10, c2=1:10, ...
      # instantiate the types
      obj1 = types[1](a1, b1, c1)
      obj2 = types[2](a2, b2, c2)
      ...

      # compose with some container type
      objs = MyType(obj1, obj2, ...)

      # plot with Plots.jl
      plot(objs)
    end
    end
  end
end

I am very new to macros and couldn’t progress much after reading the documentation online. Could someone give me a hand?

It sounds like you may be reaching for the wrong tool. “A vector of types” sounds like something that needs a function, and doesn’t make any sense from a macro.

function loop_ctor(types)
    As = [ #= define something =#(typ) for type in types ]
    # write a for loop with all variables defined above
    @manipulate for I in Iterators.product(As...)
      # instantiate the types
      objs = [ typ(I...) for typ in types ]

      # compose with some container type
      container = MyType(objs)

      # plot with Plots.jl
      plot(container)
    end
end
4 Likes