未找到前向箭头运算符

Forward arrow operator not found

我对 -> 的性质感到困惑,我无法像使用其他运算符那样获得它的定义,而且它的行为也不像 <-。见下文:

print(`<-`) # .Primitive("<-")
print(`->`) # Error in print(`->`) : object '->' not found

此外,我无法劫持它,尽管如果我尝试 R 不会引发任何错误:

`->` = `+`  # attempting to hijack `->`, no error
print(`->`) # function (e1, e2)  .Primitive("+"), seems like it worked
1 -> 3      # Error in 3 <- 1 : invalid (do_set) left-hand side to assignment
1 -> test1
print(test1) # 1, hijacking failed
`->`(1,3)   # 4, this works

使用 <-(或我尝试过的任何其他运算符),我可以做到:

`<-` = `+`   
print(`<-`)
1 <- 3      # 4
1 <- test2  # Error: object 'test2' not found

rm(list=ls()) # back to sanity

所以这是怎么回事?

> e <- quote(42 -> x)
> e
x <- 42

R 中只有一个赋值运算符:<-(好吧,两个:有 = 但我们不要把事情复杂化)。 解析器 将符号“->”解释为赋值,并像使用了 <- 一样创建表达式。

评论多于答案,但可能太长了。

看来->是由解析器处理的,解析器检测赋值的左右两边,然后调用<-。关注您的技巧:

`<-` = `+`
1 -> 3
#[1] 4

看看发生了什么? -> 运算符基本上没有时间执行,因为解析器不允许这样做,除非您显式调用它:

`->` = `+`
`->`(5,6)
#[1] 11