Chris Rackauckas
Chris Rackauckas

Reputation: 19152

Interpolating an expression into an expression inside of a quote

This question builds off of a previous SO question which was for building expressions from expressions inside of of a macro. However, things got a little trucker when quoting the whole expression. For example, I want to build the expression :(name=val). The following:

macro quotetest(name,val)
  quote
    nm = Meta.quot($(QuoteNode(name)))
    v = Meta.quot($(QuoteNode(val)))
    println(nm); println(typeof(nm))
    println(v); println(typeof(val))
  end
end

@quotetest x 5 # Test case: build :(x=5)

prints out

:x
Expr
$(Expr(:quote, 5))
Expr

showing that I am on the right path: nm and val are the expressions that I want inside of the quote. However, I can't seem to apply the previous solution at this point. For example,

macro quotetest(name,val)
  quote
    nm = Meta.quot($(QuoteNode(name)))
    v = Meta.quot($(QuoteNode(val)))
    println(nm); println(typeof(nm))
    println(v); println(typeof(v))
    println(:($(Expr(:(=),$(QuoteNode(nm)),$(QuoteNode(val))))))
  end
end

fails, saying nm is not defined. I tried just interpolating without the QuoteNode, escaping the interpolation $(esc(nm)), etc. I can't seem to find out how to make it build the expression.

Upvotes: 4

Views: 357

Answers (1)

Fengyang Wang
Fengyang Wang

Reputation: 12051

I think you are using $ signs more than you need to. Is this what you're looking for?

julia> macro quotetest(name,val)
           quote
               expr = :($$(QuoteNode(name)) = $$(QuoteNode(val)))
               println(expr)
               display(expr)
               println(typeof(expr))
           end
       end
@quotetest (macro with 1 method)

julia> @quotetest test 1
test = 1
:(test = 1)
Expr

Upvotes: 3

Related Questions