Как написать метод zipWith, который возвращает тот же тип коллекции, что и переданные ему?

Я дошел до этого:

implicit def collectionExtras[A](xs: Iterable[A]) = new {
  def zipWith[B, C, That](ys: Iterable[B])(f: (A, B) => C)(implicit cbf: CanBuildFrom[Iterable[A], C, That]) = {
    val builder = cbf(xs.repr)
    val (i, j) = (xs.iterator, ys.iterator)
    while(i.hasNext && j.hasNext) {
      builder += f(i.next, j.next)
    }
    builder.result
  }
}
// collectionExtras: [A](xs: Iterable[A])java.lang.Object{def zipWith[B,C,That](ys: Iterable[B])(f: (A, B) => C)(implicit cbf: scala.collection.generic.CanBuildFrom[Iterable[A],C,That]): That}

Vector(2, 2, 2).zipWith(Vector(4, 4, 4))(_ * _)
// res3: Iterable[Int] = Vector(8, 8, 8)

Теперь проблема в том, что указанный выше метод всегда возвращает Iterable . Как мне заставить его возвращать коллекцию типов в том виде, в каком они были переданы ему? (в данном случае Vector ) Спасибо.

11
задан Eugene Yokota 15 December 2010 в 19:31
поделиться