Saturday 3 January 2015

How a for loop is translated



1. How a for loop is translated under various conditions.

  1. A simple for loop that iterates over a collection is translated to a foreach method call on the collection.
  2. A for loop with a guard (see Recipe 3.3) is translated to a sequence of a withFilter method call on the collection followed by a foreach call.
  3. A for loop with a yield expression is translated to a map method call on the collection.
  4. A for loop with a yield expression and a guard is translated to a withFilter method call on the collection, followed by a map method call.

For example, the below two statements are equal.
scala> val out = for (e <- fruits) yield e.toUpperCase
scala> val out = fruits.map(_.toUpperCase)

The way to check these:

class Main {
  for (i <- 1 to 10) println(i)
}

$ scalac -Xprint:parse Main.scala



2. A 
yield statement with a for loop and your algorithm to create a new collection from an existing collection. 


  • When it begins running, the for/yield loop immediately creates a new, empty collection that is of the same type as the input collection. For example, if the input type is a Vector, the output type will also be a Vector. You can think of this new collection as being like a bucket.
  • On each iteration of the for loop, a new output element is created from the current element of the input collection. When the output element is created, it’s placed in the bucket.
  • When the loop finishes running, the entire contents of the bucket are returned.

No comments:

Post a Comment