为什么允许:=作为中缀运算符? [英] Why is := allowed as an infix operator?

查看:75
本文介绍了为什么允许:=作为中缀运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了流行的 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的某些解析特性?是hack吗?将来会修补吗?

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

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