Why is := allowed as an infix operator?

后端 未结 2 521
一整个雨季
一整个雨季 2020-12-03 16:47

I have come across the popular data.table package and one thing in particular intrigued me. It has an in-place assignment operator

:=

2条回答
  •  情书的邮戳
    2020-12-03 17:45

    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
    

    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.

提交回复
热议问题