Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse implementation Seq

Tags:

scala

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

like image 889
Jatin Avatar asked Sep 12 '26 11:09

Jatin


1 Answers

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
}
like image 84
Rex Kerr Avatar answered Sep 15 '26 00:09

Rex Kerr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!