How to interpolate symbol as symbol, not as variable name?


#1

Given a list of keys, I want to generate expressions for getting the keys from a predefined dictionary. E.g. for string keys:

ks = ["x", "y"]
result = [:(d[$k]) for k in ks]
# ==> 2-element Array{Expr,1}:                                                                                                                                                                                    
# ==>   :(d["x"])                                                                                                                                                                                                         
# ==>   :(d["y"])

Now let’s change key type to Symbol:

ks = [:x, :y]
result = [:(d[$k]) for k in ks]
# ==>  2-element Array{Expr,1}:                                                                                                                                                                                           
# ==>    :(d[x])                                                                                                                                                                                                           
# ==>    :(d[y])

Oops, Julia thinks I want variables x and y instead of constants :x and :y. Is there a way to fix it?


A couple of things I have already tried:

  • :(d[$(esc(k))]) gives :(d[$(Expr(:escape, :x))]) which evaluates to “invalid syntax” error
  • :(d[Symbol("$k")]) gives :(d[Symbol("$(k)")]) which evaluates to “k not defined” error

#2

Either use [:(d[$(QuoteNode(k)]) for k in ks] or [:(d[$(Expr(:quote, k))]) for k in ks]. I think they’re equivalent…


#3

Perfect, thanks!