在 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 language definition 中找到。 ,但它的目的恰恰是为了保留原始来源的结构,尤其是注释;例如
s <- substitute(function(x=1){
## a comment
x^2})
str(s[[4]])
## Class 'srcref' atomic [1:8] 1 21 2 15 21 15 1 2
## ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x8a87634>
显示它是
srcref
目的。如 ?srcfile 中所述,神秘数字 (1, 21, 2, 15, ...) 表示代表源代码的低级对象的索引。页(即 c(first_line, first_byte, last_line, last_byte, first_column, last_column, first_parsed, last_parsed)
)。正如@SimonO101 指出的那样,有一个 R Journal article by Duncan Murdoch这可能给出了最好的解释。
关于R中函数解析树的冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17053765/