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

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.)



Solution 1:[1]

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)

Solution 2:[2]

Another shorter possibility:

    macro mymacro(ex)
           QuoteNode(ex)
    end

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Høegh
Solution 2 DMeneses