Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

macros

julia

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

like image 247
Pietro Braione Avatar asked Dec 24 '22 18:12

Pietro Braione


1 Answers

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)
like image 125
Daniel Høegh Avatar answered Jan 12 '23 18:01

Daniel Høegh