【问题标题】:Forward arrow operator not found未找到前进箭头运算符
【发布时间】:2017-12-08 23:20:01
【问题描述】:

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

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

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

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

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

那么发生了什么?

【问题讨论】:

    标签: r operators assignment-operator


    【解决方案1】:

    更多的是评论而不是答案,但它可能太长了。

    看来-&gt;是由解析器处理的,它检测到赋值的左右两边,然后调用&lt;-。跟随你的黑客:

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

    看看发生了什么? -&gt; 操作符基本上没有时间采取行动,因为解析器不允许这样做,除非你明确地调用它:

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

    【讨论】:

      【解决方案2】:
      > e <- quote(42 -> x)
      > e
      x <- 42
      

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

      【讨论】:

        猜你喜欢
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 2013-07-16
        • 2012-12-04
        • 1970-01-01
        相关资源
        最近更新 更多