Wednesday, October 05, 2011

Scala By Example Chapter 11 Solutions - Exercise 11.2.1

Exercise 11.2.1 Write a function repeatLoop with also additional syntax for an until clause.

The repeat { command } until (condition) was tricky. The trick is to realize that "until" would be a method call, and for it to be a method call, "repeat {command}" would have to be an object. Since objects are created using new, we could wrap this object creation with a method. The result is below. Note that the second method has been changed to repeatUntilLoop since it would conflict with the previous method repeatUntil.

object FunctionalLoops {
def repeatLoop(command: => Unit)(condition: => Boolean) {
command
if (condition) {
repeatLoop(command)(condition)
} else ()
}
def repeatUntilLoop(command: => Unit) = {
class RepeatUntilLoopClass(command: => Unit) {
def until(condition: => Boolean): Unit = {
command
if (!condition) {
until(condition)
} else ()
}
}
new RepeatUntilLoopClass(command)
}
def main(args: Array[String]) {
var i = 10;
repeatLoop { i -= 1; println(i) } (i > 0)
var j = 1;
repeatUntilLoop { j += 10; println(j) } until (j >= 100)
}
}

No comments: