Julia:如何创建一个返回其参数的宏? [英] Julia: How do I create a macro that returns its argument?

查看:9
本文介绍了Julia:如何创建一个返回其参数的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与 this 非常相似一个,但有区别.我想创建一个以这种方式运行的宏(或其他):

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)

这篇关于Julia:如何创建一个返回其参数的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆