4

如何在Scala集合上添加foreachWithIndex方法?用方法丰富Scala集合

这是我能想出迄今:

implicit def iforeach[A, CC <: TraversableLike[A, CC]](coll: CC) = new { 
    def foreachWithIndex[B](f: (A, Int) => B): Unit = { 
    var i = 0 
    for (c <- coll) { 
     f(c, i) 
     i += 1 
    } 
    } 
} 

这不起作用:

Vector(9, 11, 34).foreachWithIndex { (el, i) => 
    println(el, i) 
} 

引发以下错误:

error: value foreachWithIndex is not a member of scala.collection.immutable.Vector[Int] 
Vector(9, 11, 34).foreachWithIndex { (el, i) => 

然而代码当我明确应用转换方法时工作:

iforeach[Int, Vector[Int]](Vector(9, 11, 34)).foreachWithIndex { (el, i) => 
    println(el, i) 
} 

输出:

(9,0) 
(11,1) 
(34,2) 

我如何让它度过,即使没有一个转换方法的明确的应用吗?谢谢。

回答

8

您需要延长的Iterable:

class RichIter[A, C](coll: C)(implicit i2ri: C => Iterable[A]) { 
    def foreachWithIndex[B](f: (A, Int) => B): Unit = { 
    var i = 0 
    for (c <- coll) { 
     f(c, i) 
     i += 1 
    } 
    } 
} 

implicit def iter2RichIter[A, C[A]](ca: C[A])(
    implicit i2ri: C[A] => Iterable[A] 
): RichIter[A, C[A]] = new RichIter[A, C[A]](ca)(i2ri) 

Vector(9, 11, 34) foreachWithIndex { 
    (el, i) => println(el, i) 
} 

输出:

(9,0) 
(11,1) 
(34,2) 

更多信息请参见this post by Rex Kerr

4

简短的回答是,如果你这样做,或者类型推理器不能确定A是什么,你必须参数化CC。另一个简短的回答就是我在this question的回答中描述的方式。

要展开多一点点,真的没有理由,你需要CC <: TraversableLike --just有它采取Traversableiforeach[A](coll: Traversable[A])开始!您不需要使用花式类型边界来使用超类/超类。如果您希望在保存集合类型的情况下返回其他集合的情况下执行更复杂的操作,那么您需要使用构建器等,这些在另一个问题中描述。

+0

其实它是由一组额外的方法只有一个方法我我正在努力实施。其他一些方法需要构建相同类型的新集合。 – missingfaktor

2

如果您感兴趣的是只有一个指标迭代什么,你还不如干脆跳过这个拉皮条的一部分,这样做

coll.zipWithIndex.foreach { case (elem, index) => 
    /* ... */ 
} 
+0

https://twitter.com/#!/missingfaktor/status/95597737680183297 :-) – missingfaktor

+0

那么'mapWithIndex'呢?名单继续。 –