在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}
Run Code Online (Sandbox Code Playgroud)
我注意到的一件事是第四个元素确实存储了输入函数的格式.
> as.list(substitute(function(x = 1){
+ x^2})[[4]]
function(x = 1){
x^2}
Run Code Online (Sandbox Code Playgroud)
解析树中第四个元素的目的是什么?我唯一能看到它被使用的是你想要逐字打印一个函数,你已经可以通过打印函数来完成,例如
> f = function(x = 1){
+ x^2}
> f
function(x = 1){
x^2}
Run Code Online (Sandbox Code Playgroud)
显然这个组件是一个源参考:它不容易位于R语言定义中,但其目的恰恰是保留原始源的结构,尤其是注释; 例如
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>
Run Code Online (Sandbox Code Playgroud)
表明它是一个srcref对象.神秘的数字(1,21,2,15,...)表示代表源代码的低级对象的索引,如?srcfile页面(即c(first_line, first_byte, last_line, last_byte, first_column, last_column, first_parsed, last_parsed))中所述.正如@ SimonO101指出的那样,Duncan Murdoch撰写的R Journal文章可能给出了最好的解释.