Reputation: 134
I am trying to learn scala. I was looking at the documentation for queues (https://www.scala-lang.org/api/current/scala/collection/immutable/Queue.html).
It is my understanding that methods that end in a colon are right associative. However, to me, the ++: does not apear to do so:
import scala.collection.immutable.Queue
val q0 = Queue(0)
val q1 = Queue(1)
q0 ++ q1 // yields Queue(0,1) as I expected
q0 ++: q1 // yields Queue(0,1) as well; I expected Queue(1,0)
Both the documentation and experimentation seem to indicate that ++: is not right associative. The documentation for both ++ and ++: say left followed by the right and that is what happens above, I just don't understand why. Clearly, there is something I am missing. Could someone please clarify this for me?
Upvotes: 0
Views: 109
Reputation: 44957
A very simple experiment:
case class A(s: String) { def ++:(a: A) = A(s"(${a.s} + ${s})") }
A("x") ++: A("y") ++: A("z")
gives:
A((x + (y + z)))
so it's x + (y + z)
and not (x + y) + z
. Thus, the ++:
is right-associative, as advertised.
Note that it's ${a.s} + ${s}
and not ${s} + ${a.s}
. In the case of Queue
, it's probably analogous, something like:
def ++:(left: Queue[A]): Queue[A] = left ++ this
so the order of elements appears "as it should be" when you write q0 ++: q1
which desugars into q1.++:(q0)
and then expands into q0 ++ q1
.
Upvotes: 4