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

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

问题描述

我的问题与这很相似一个,但有所不同.我想创建一个行为如下的宏(或其他任何东西):

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屋!

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