Jatin
Jatin

Reputation: 31724

reverse implementation Seq

In the class SeqLike.scala there is a function called reverse which reverses a sequence. For example it makes List(1,2,3,4) to `List(4,3,2,1)

In the source, the description is:

def reverse: Repr = {
var xs: List[A] = List() //Line 1
for (x <- this)
  xs = x :: xs
val b = newBuilder ////Line 4
b.sizeHint(this)
for (x <- xs)
  b += x
b.result
}

What I dont understand, is: Line (1-3) does the job. But why does it make a new builder and then add elements to it to return. Just Line[1-3] will suffice

Upvotes: 3

Views: 935

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167871

Lines 1-3 generate a List. But reverse is not supposed to return any old Seq but the same type of Seq as it got. So if it's actually a list it doesn't need the extra builder step; otherwise it does. (And if you look in the implementation of List, it doesn't do the extra work.)

override def reverse: List[A] = {
  var result: List[A] = Nil
  var these = this
  while (!these.isEmpty) {
    result = these.head :: result
    these = these.tail
  }
  result
}

Upvotes: 6

Related Questions