Julia: How do I create a macro that returns its argument?

261 views Asked by At

My question is quite similar to this one, but with a difference. I want to create a macro (or whatever) that behaves this way:

julia> @my-macro x + 2
:(x + 2)

(note that x + 2 is not enclosed in quotes). Is there something like that in Julia? And if there is not, how do I do it? (Please, give a detailed explanation about why it works.)

2

There are 2 answers

0
Daniel Høegh On BEST ANSWER

The input expression to the macro needs to be quoted because a macro returns an expression, which are evaluated, while you would like to get the expression itself, hence you need an extra quoting. The quoting can be done as:

macro mymacro(ex)
    Expr(:quote,ex) # this creates an expression that looks like :(:(x + 2))
end
e=@mymacro x + 2 #returns :(x + 2)
0
DMeneses On

Another shorter possibility:

    macro mymacro(ex)
           QuoteNode(ex)
    end

    e = @mymacro x + 2 #returns :(x + 2)