朱莉娅:如何创建一个返回其参数的宏? [英] 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)
(请注意,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.)
推荐答案
宏的输入表达式需要用引号引起来,因为宏会返回一个表达式,该表达式将被求值,而您希望获得表达式本身,因此您需要额外的报价.引用可以这样完成:
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)
这篇关于朱莉娅:如何创建一个返回其参数的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!