How to make a vector of symbols using a macro

How do I make a vector of symbols using a macro?

macro foo()
    Expr(:vect, :x1, :x2)
end

julia> @foo
ERROR: UndefVarError: x1 not defined

Clearly this making the expression [x1, x2]. However I would like to make the vector [:x1, :x2]. I can’t figure out how to make this work, can someone help me out?

Is this what you are looking for?

julia> macro foo()
           Expr(:vect, Symbol(x1), Symbol(x2) )
       end
@foo (macro with 1 method)

julia> @foo
2-element Array{Symbol,1}:
 :x1
 :x2

I think the insight you’re missing is how to use QuoteNode to deal with the distinction between symbols (since every identifier is just a symbol in an Expr object) and quoted symbols:

macro foo()
    Expr(:vect, QuoteNode(:x1), QuoteNode(:x2))
end
1 Like