Julia: How to create a macro that returns its argument?

My question is very similar to this , but with a difference. I want to create a macro (or whatever) that behaves as follows:

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

(note that x + 2 is not enclosed in quotation marks). Is there something similar in Julia? And if not, how can I do this? (Please give a detailed explanation of why it works.)

+4
source share
1 answer

The input expression needs to be specified for the macro, because the macro returns the expression that is evaluated, while you want to get the expression itself, so you need additional quoting. 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)
+9
source

All Articles