【发布时间】:2013-06-11 21:02:52
【问题描述】:
在 R 中,我注意到 function 运算符的解析树似乎是多余的,因为它的第四个元素似乎总是由前三个元素组成。
例如,
> as.list(substitute(function(x = 1){x^2}))
[[1]]
`function`
[[2]]
[[2]]$x
[1] 1
[[3]]
{
x^2
}
[[4]]
function(x = 1){x^2}
我注意到的一件事是第四个元素确实存储了输入函数的格式。
> as.list(substitute(function(x = 1){
+ x^2})[[4]]
function(x = 1){
x^2}
解析树中第四个元素的用途是什么?我唯一能看到它被使用的是如果你想逐字打印一个函数,你已经可以通过打印函数来做到这一点,例如
> f = function(x = 1){
+ x^2}
> f
function(x = 1){
x^2}
【问题讨论】:
-
好问题;我在 R 语言定义中找不到任何东西,但我认为保留源引用正是为了能够保留(例如)cmets;如果我做
s <- substitute(function(x=1){ ## a comment; x^2})(在分号处换行),那么str(s[[4]])表明它是一个srcref对象。srcref类的方法看起来真的很神秘......(文档:stat.ethz.ch/R-manual/R-patched/library/base/html/srcfile.html) -
另一个有趣的事情是在第四个元素上执行
as.list,虽然我不知道结果列表代表什么。 -
@Ben 说得对。要确认第四个元素确实只是一个 srcref,请查看执行操作时会得到什么:
options(keep.source=FALSE); as.list(substitute(function(x = 1){x^2}))。 (或者只检查第四个元素的类!) -
@JonClaus:
as.list(s[[4]])中描述了as.list(s[[4]])结果的含义:c(first_line, first_byte, last_line, last_byte, first_column, last_column, first_parsed, last_parsed)指的是代表源代码的低级对象的索引。 -
@BenBolker:您不应该将您的 cmets 粘贴到答案面板中吗?
标签: r parse-tree