Chapter 3, Exercise 4, Thinking in Scala
This exercise is just to show what a Java for loop is like. Now, in Scala, the underlying mechanism is completely different, acting more like a "list comprehension" as in Haskell or Python and involving a translation into some method calls (.filter, .flatMap, .map, et al.). Despite this, the Scala for loop can be made to look pretty innocuous.
package x;
object c3x4 {
def main ( args : Array[String] ) =
for (val i <- Iterator.range(1,101) )
Console.println( i );
}
As a bonus, here's a definition of a loop construct that I made to look more like the C/C++/Java for loop:
object c3x4_bonus {
def cFor (def init:unit) (def p: boolean)
(def incr:unit) (def s: unit): unit =
{
init; while(p) { s ; incr }
}
def main ( args : Array[String] ) = {
var i: Int = _;
cFor (i= 1)(i < 100)(i= i+1) {
Console.println( i );
}
}
}
Foreshadowing: note that the break
statement is somewhat troublesome, given the semantics of Scala's for loops.
12:44:13 AM