Lists and vectors
List and Vector are the two sequences a Scala program reaches for. A list is a linked list: the first element and the rest, with a cost that follows from that shape. A vector is a tree of thirty-two-way nodes: it indexes like an array and appends without copying the whole sequence. Both are immutable, and both share structure with the collection they came from.
A list and its ends
:: puts an element in front and is the constructor of the list, so 0 :: numbers is a new list that shares the tail of the old one. Nil is the empty list, and the methods a program uses most read the ends:
lists.scala
@main def lists(): Unit =
val numbers = List(1, 2, 3)
val more = 0 :: numbers
println(more)
println(more.head)
println(more.tail)
println(more ++ List(4, 5))
println(more :+ 9)
println(more.length)
println(more.reverse)
println(more(2))
println(Nil)
println(List.fill(3)("x"))
println(more.map(_ * 10))
println(numbers.exists(_ > 2))
scala-cli run --server=false lists.scala
List(0, 1, 2, 3)
0
List(1, 2, 3)
List(0, 1, 2, 3, 4, 5)
List(0, 1, 2, 3, 9)
4
List(3, 2, 1, 0)
2
List()
List(x, x, x)
List(0, 10, 20, 30)
true
head and tail are constant time, and so is ::; :+ has to walk the whole list to reach the end, and indexing with more(2) walks to that position. The list in the example is short enough that the cost does not show. A program that appends in a loop builds a list in reverse and reverses it once at the end, which is why reverse is in the toolbox.
A vector and the cost of both
A vector answers v(0) and v :+ 4 without copying, and updated returns a new vector that shares almost all of its structure with the old one. The printed value says which collection a transformation returned:
vectors.scala
@main def vectors(): Unit =
val v = Vector(1, 2, 3)
println(v)
println(v :+ 4)
println(5 +: v)
println(v.updated(0, 9))
println(v(0))
println(v ++ Vector(7, 8))
println(v.take(2))
println(v.map(_ * 2))
println(v.zip(Vector("a", "b", "c")))
scala-cli run --server=false vectors.scala
Vector(1, 2, 3)
Vector(1, 2, 3, 4)
Vector(5, 1, 2, 3)
Vector(9, 2, 3)
1
Vector(1, 2, 3, 7, 8)
Vector(1, 2)
Vector(2, 4, 6)
Vector((1,a), (2,b), (3,c))
The rule of thumb is short. Prepend to a list, and use a list when the program walks it from the front; use a vector when it indexes, appends or updates, which is most of the time. List is the default for a small sequence and for a recursive function that matches head :: tail; Vector is the default for a large one. Neither is changed in place, so a collection passed to another method cannot be modified behind the caller's back.
Related
- map, flatMap, filter and fold: what is done with a list once it exists.
- Tail recursion: the head :: tail pattern over a list.
- Sets and maps: the collections with a key.
- Java: ArrayList and LinkedList, which are changed in place.
Article author: Arthur Isaev