Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an autoincrement index in for comprehension in Scala

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)
like image 779
Matroska Avatar asked Feb 18 '12 16:02

Matroska


2 Answers

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)
like image 119
tenshi Avatar answered Sep 19 '22 11:09

tenshi


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.

like image 22
jxstanford Avatar answered Sep 22 '22 11:09

jxstanford