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

后端 未结 1 1115
死守一世寂寞
死守一世寂寞 2021-01-14 02:43

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          


        
1条回答
  •  囚心锁ツ
    2021-01-14 03:33

    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 讨论(0)
提交回复
热议问题