如何在Scala中使用自动增量索引来理解

时间:2012-02-18 16:02:47

标签: scala for-comprehension

是否可以在Scala中使用自动增量计数器进行理解?

类似

for (element <- elements; val counter = counter+1) yield NewElement(element, counter)

2 个答案:

答案 0 :(得分:15)

我相信,您正在寻找List和其他收藏品上提供的zipWithIndex方法。以下是它的用法的一个小例子:

scala> val list = List("a", "b", "c")
list: List[java.lang.String] = List(a, b, c)

scala> list.zipWithIndex
res0: List[(java.lang.String, Int)] = List((a,0), (b,1), (c,2))

scala> list.zipWithIndex.map{case (elem, idx) => elem + " with index " + idx}
res1: List[java.lang.String] = List(a with index 0, b with index 1, c with index 2)

scala> for ((elem, idx) <- list.zipWithIndex) yield elem + " with index " + idx
res2: List[java.lang.String] = List(a with index 0, b with index 1, c with index 2)

答案 1 :(得分:2)

理解并不像for循环,因为术语是针对每个前一个术语进行评估的。例如,请查看下面的结果。我认为这不是你想要的:

    scala> val elements = List("a", "b", "c", "d")
elements: List[java.lang.String] = List(a, b, c, d)

scala> for (e <- elements; i <- 0 until elements.length) yield (e, i)
res2: List[(java.lang.String, Int)] = List((a,0), (a,1), (a,2), (a,3), (b,0), (b,1), (b,2), (b,3), (c,0), (c,1), (c,2), (c,3), (d,0), (d,1), (d,2), (d,3))
对于你期望的结果,tenshi的回答可能更加正确,但我希望这个反例很有用。