[beginning-scala-programming] Loops


 var i=0
 while(i<5) {
   println(i)
   i += 1
 }
 for(i<- 0 until 5) {
   println(i)
 }

 val a = Array.fill(5)(math.random)
 for(x <- a) println(x)
scala> 1 to 5
res1: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)

scala> 0 until 5
res2: scala.collection.immutable.Range = Range(0, 1, 2, 3, 4)

yield

 for(x <- a) yield x*x
 a.map(x => x*x) // same
 // Array[Double] = Array(0.22942607856489816, 0.42670896833696664, 0.2115497274377164, 0.4793313932180108, 0.0640459561805972)

 for(i <- 0 until 5; j<- 5 until 10) yield (i,j)
 //scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,5), (0,6), (0,7), (0,8), (0,9), (1,5), (1,6), (1,7), (1,8), (1,9), (2,5), (2,6), (2,7), (2,8), (2,9), (3,5), (3,6), (3,7), (3,8), (3,9), (4,5), (4,6), (4,7), (4,8), (4,9))
 for(i <- 0 until 5; a = 2*i; j<- 5 until 10) yield (a,j)
 // for 문 안에서도 연산 가능

 for(i <- 0 until 5; if i%2==0; j<- 5 until 10) yield (a,j)
 // for 문 안에서도 filter도 가능


 // {}로 바꾸면 ;(세미콜론) 생략 가능
 for { i <- 0 until 5
     if i%2 ==0
     a = 2 * i
     j <- 5 until 10 } yield (a,j)


 // parallel 하게도 가능
 for { i <- (0 until 5).par
       if i%2 ==0
       a = 2 * i
       j <- 5 until 10 } yield (a,j)
 // scala.collection.parallel.immutable.ParSeq[(Int, Int)] = ParVector((0,5), (0,6), (0,7), (0,8), (0,9), (4,5), (4,6), (4,7), (4,8), (4,9), (8,5), (8,6), (8,7), (8,8), (8,9))
 // return 값도 scala.collection.parallel.immutable.ParSeq 로 변함.