3

虽然三重冒号是右结合运算符,但下面的结果表明它不是真的,是吗?

List(3, 4, 5) ::: List(18, 19, 20) //> List[Int] = List(3, 4, 5, 18, 19, 20)

从我的角度来看,结果应该是List(18, 19, 20, 3, 4, 5)因为它与说:

List(18, 19, 20).:::(List(3, 4, 5))

我是否理解正确联想错误的定义?

4

2 回答 2

5

从文档:

def :::(prefix: List[A]): List[A]
[use case] Adds the elements of a given list in front of this list.

例子:

List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)
prefix  - The list elements to prepend.
returns - a list resulting from the concatenation of the given list prefix and this list.

这说明了一切。至于右关联操作,你的 r 是对的。

于 2013-07-20T07:33:00.773 回答
1

关联性与表达式无关

x ::: y

的关联性:::决定了是否

x ::: y ::: z

被解释为(如果是左结合)

( x ::: y ) ::: z

或作为(如果是右结合)

x ::: ( y ::: z )

因为在 Scala 中,所有以冒号结尾的运算符都是右结合的,所以使用后一种解释:假设 x,y,z 是 List 类型的变量,首先 y 附加到 z 前面,然后 x 附加到那个前面。

于 2013-07-21T06:16:33.327 回答