为什么 := 允许作为中缀运算符? [英] Why is := allowed as an infix operator?
问题描述
我遇到了流行的 data.table
包,其中一件事特别让我感兴趣.它有一个就地赋值运算符
I have come across the popular data.table
package and one thing in particular intrigued me. It has an in-place assignment operator
:=
这在基础 R 中没有定义.事实上,如果您没有加载 data.table
包,如果您尝试使用它会引发错误(例如,a := 2
) 与消息:
This is not defined in base R. In fact if you didn't load the data.table
package, it would have raised an error if you had tried to used it (e.g., a := 2
) with the message:
错误:找不到函数 ":="
另外,为什么 :=
有效?为什么 R 允许您将 :=
定义为中缀运算符,而其他所有中缀函数都必须被 %%
包围,例如
Also, why does :=
work? Why does R let you define :=
as infix operator while every other infix function has to be surrounded by %%
, e.g.
`:=` <- function(a, b) {
paste(a,b)
}
"abc" := "def"
很明显,它并不是用于定义中缀函数的 %function.name%
的替代语法.data.table
是否利用了 R 的一些解析怪癖?是黑客吗?以后会打补丁"吗?
Clearly it's not meant to be an alternative syntax to %function.name%
for defining infix functions. Is data.table
exploiting some parsing quirks of R? Is it a hack? Will it be "patched" in the future?
推荐答案
这是基本 R 解析器识别的东西,并且似乎解析为左分配(至少在操作的顺序等方面).有关详细信息,请参阅 C 源代码.
It is something that the base R parser recognizes and seems to parse as a left assign (at least in terms or order of operations and such). See the C source code for more details.
as.list(parse(text="a:=3")[[1]])
# [[1]]
# `:=`
#
# [[2]]
# a
#
# [[3]]
# [1] 3
据我所知,它是无证的(就基本 R 而言).但它是一个可以改变其行为的函数/运算符
As far as I can tell it's undocumented (as far as base R is concerned). But it is a function/operator you can change the behavior of
`:=`<-function(a,b) {a+b}
3 := 7
# [1] 10
如您所见,:"部分本身并没有什么特别之处.它恰好是复合标记的开始.
As you can see there really isn't anything special about the ":" part itself. It just happens to be the start of a compound token.
这篇关于为什么 := 允许作为中缀运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!