6

Is it true that applying the list1 ::: list2 operator to two lists corresponds to appending all of the contents of list1 to list2?

scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)

scala> val b = List(4,5,6)
b: List[Int] = List(4, 5, 6)

scala> a:::b
res0: List[Int] = List(1, 2, 3, 4, 5, 6)

Is there any other use for this operator? I could not find anything on ::: in the Scala documentation and am wondering the extent of its formal name and use.

rookie
  • 2,783
  • 5
  • 29
  • 43
  • yes seems to be just a list-concetenation - found it: http://www.tutorialspoint.com/scala/scala_lists.htm - and yes it's just that – Random Dev Oct 15 '14 at 05:31
  • 1
    Did you look at the [API reference for `List`](http://www.scala-lang.org/api/current/#scala.collection.immutable.List)? – Chris Martin Oct 15 '14 at 05:34
  • possible duplicate of [Scala list concatenation, ::: vs ++](http://stackoverflow.com/questions/6559996/scala-list-concatenation-vs) – The Archetypal Paul Oct 15 '14 at 19:03

1 Answers1

10

Yes, it is just the list concatenation operator. They are nil terminated linked lists so conceptually all it is really doing is taking the last cons cell of the first list and pointing it to the head of the second list instead of Nil.

You can also use the more generic ++ operator instead of ::: if you prefer. The end result is the same but technically you are making calls on different objects. Operators ending in a : are right associative in Scala so using a ++ b is the same as a.++(b) or basically a.append(b) as opposed to a ::: b being right associative is translated to b.:::(a) which can be read as b.prepend(a).

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
Shane Delmore
  • 1,575
  • 2
  • 13
  • 19
  • This simplification is somewhat disingenuous as it conceals the linear runtime. – Chris Martin Oct 15 '14 at 05:40
  • I did not intend to be misleading by not discussing the performance of the current implementation, you make a good point about the performance being surprising to some people. – Shane Delmore Oct 15 '14 at 05:43