Is it possible to use an autoincrement counter in for comprehensions in Scala?
something like
for (element <- elements; val counter = counter+1) yield NewElement(element, counter)
I believe, that you are looking for zipWithIndex
method available on List and other collections. Here is small example of it's usage:
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)
A for comprehension is not like a for loop in that the terms are evaluated for each previous term. As an example, look at the results below. I don't think that's what you are looking 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's answer is probably more on track with your desired result, but I hope this counterexample is useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With