A srinivas
A srinivas

Reputation: 851

What is the need of linear sequence List when there is Vector?

Vector is immutable,indexed,supports random access,efficient in Scala ; what is the need of immutable linear sequence List?

Upvotes: 1

Views: 92

Answers (3)

raphaëλ
raphaëλ

Reputation: 6523

In addition to what @marios and @puhlen have already mentioned, another reason to use a traditional list (head/tail) is for pattern matching. There are two classes that help with this.

First there is the :: (cons) case class:

final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B] {
  override def tail : List[B] = tl
  override def isEmpty: Boolean = false
}

Second, there is a a Nil case class:

case object Nil extends List[Nothing] { 
  ...
}

(As you can see these both work on List types)

These make pattern matching on a list very natural:

list match {
  case Nil => "empty list"
  case x :: xs => s"head is $x with tail $xs"
}

Upvotes: 0

marios
marios

Reputation: 8996

There has been a very interesting Blog by Haoyi Li comparing Scala collections. I recommend this to anyone.

There is a section that explicitly compared Lists vs Vectors.

Overall, Lists and Vectors have quite different characteristics

  • Lists take about double the space compared to Vectors. So if you have millions of elements, Vectors are the way to go.
  • Random access on Vectors is effectively O(1) and on Lists O(n).
  • Growing Vectors by appending one element at the time is slow, really slow. Lists are an order of magnitude faster.
  • Sequential scanning Lists and Vectors has the same speed.

Upvotes: 1

puhlen
puhlen

Reputation: 8519

List is a very common data structure and it would be weird if it didn't exist.

List is better with prepend, head, and tail operations

List has less overhead compared to vector

If you don't need random access and only care about head/tail operations List makes sense. If you do need random access then Vector or some other data structure makes more sense.

Upvotes: 4

Related Questions