Friday, September 28, 2012

Scala Iteration - step by 2*previous loop index

I had a basic Scala related question about how to replicate the following Java loop in Scala:

for (int i=1;i<100000;i=2*i){
    System.out.println(i);
}

I knew one way to go about doing this using a recursive loop this way:

def loopByTwiceBefore(from:Int, to:Int)(f:Int=>Unit):Unit = {
    if (from<to){
        f(from)
        loopByTwiceBefore(from*2, to)(f);
    }
}
loopByTwiceBefore(1, 100000)(println)

I asked this question in StackOverflow and immediately got back two better ways of doing this:

for (n <- Iterator.iterate(1)(2*).takeWhile(100000>)) println(n)

OR

Iterator.iterate(1)(_*2).takeWhile(_ < 100000) foreach {println(_)}

and the link to the Iterator companion object at the Scala API site for more information

No comments:

Post a Comment