小编Jim*_*Jim的帖子

如何编写一个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)
Run Code Online (Sandbox Code Playgroud)

现在问题是上面的方法总是返回一个Iterable.如何让它返回传递给它的类型集合?(在这种情况下,Vector)谢谢.

scala scala-2.8 scala-collections

11
推荐指数
3
解决办法
1014
查看次数

标签 统计

scala ×1

scala-2.8 ×1

scala-collections ×1