Why is := allowed as an infix operator?

后端 未结 2 500
一整个雨季
一整个雨季 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:32

    It's not just a colon operator but rather := is a single operator formed by the colon and equal sign (just as the combination of "<" and "-" forms the assignment operator in base R). The := operator is an infix function that is defined to be part of the evaluation of the "j" argument inside the [.data.table function. It creates or assigns a value to a column designated by its LHS argument using the result of evaluating its RHS.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题