Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is zipWithIndex implemented in Iterable and not Traversable?

Tags:

scala

I'm reading "Programming in Scala 2ed". In section 24.4, it's noted that Iterable contains many method that cannot be efficiently written without an iterator. Table 24.2 contains these methods. However, I don't understand why some of them cannot be efficiently implemented on iterator. For example, consider zipWithIndex.

  def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = {
    val b = bf(repr)
    var i = 0
    for (x <- this) {
      b += ((x, i))
      i +=1
    }
    b.result
  }

Why not move this definition to traversable? It seems to me that the code could be exactly the same and there would be no difference in efficienty.

like image 680
schmmd Avatar asked Nov 06 '11 05:11

schmmd


1 Answers

You're completely correct, and your implementation should work. No good reason to have zipWithIndex defined in Iterable and not Traversable; neither makes any guarantee about the ordering of the elements under traversal.

(This is my first answer on StackOverflow. Hope I've been helpful. :) If I've not, please tell me.)

like image 109
Harrison Avatar answered Sep 20 '22 07:09

Harrison