GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Thursday 6 May 2004
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   comment/     



Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/2/6; 12:39:00 .
Click here to send an email to the editor of this weblog.

May 2004
Sun Mon Tue Wed Thu Fri Sat
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31          
Apr   Jun

Previous/Next