diff --git a/src/main/scala/internal/ForLoop.scala b/src/main/scala/internal/ForLoop.scala index f80286b..06ad45b 100644 --- a/src/main/scala/internal/ForLoop.scala +++ b/src/main/scala/internal/ForLoop.scala @@ -1,7 +1,7 @@ package internal /** - * the loop body should execute 5 times and print: + * the loop body should execute 10 times and print: * 0 * 2 * 4 @@ -11,7 +11,13 @@ package internal object ForLoop extends App { - // define the new control-flow structure here + def for_loop(initializer: ⇒Unit)(condition: ⇒Boolean)(increment: ⇒Unit)(body: ⇒Unit) = { + initializer + while (condition) { + body + increment + } + } var i = 0; for_loop(i = 0)(i < 10)(i += 2) { diff --git a/src/main/scala/internal/LoopUntil.scala b/src/main/scala/internal/LoopUntil.scala index d12efb4..b308a42 100755 --- a/src/main/scala/internal/LoopUntil.scala +++ b/src/main/scala/internal/LoopUntil.scala @@ -10,7 +10,11 @@ package internal */ object LoopUntil extends App { - // define the new control-flow structure here + def loop_until(condition: ⇒Boolean)(body: ⇒Unit) = { + while (!condition) { + body + } + } var i = 0 diff --git a/src/main/scala/internal/RepeatUntil.scala b/src/main/scala/internal/RepeatUntil.scala index 8e033ff..9ba7077 100755 --- a/src/main/scala/internal/RepeatUntil.scala +++ b/src/main/scala/internal/RepeatUntil.scala @@ -11,13 +11,33 @@ package internal object RepeatUntil extends App { - // define the new control-flow structure here + class RepeatClass(body: ⇒Unit) { + def until(condition: ⇒Boolean) = { + do { + body + } while(!condition) + } + } + + def repeat(body: ⇒Unit) = new RepeatClass(body) + + /** + * Alternative definition, using a new feature -- implicit classes -- + * that was recently added to Scala + */ + /* implicit class repeat(body: ⇒Unit) { + def until(condition: ⇒Boolean) = { + do { + body + } while(!condition) + } + }*/ var i = 0 repeat { if ( (i % 2) == 0 ) println(i) i += 1 - } until(i > 9) + } until(i > 9) } diff --git a/src/main/scala/internal/WhileContinue.scala b/src/main/scala/internal/WhileContinue.scala index 8f6ee74..4d40f4a 100755 --- a/src/main/scala/internal/WhileContinue.scala +++ b/src/main/scala/internal/WhileContinue.scala @@ -11,7 +11,20 @@ package internal object WhileContinue extends App { - // define the new control-flow structures here + object ContinueException extends Exception + + def continue = throw ContinueException + + def while_c(condition: ⇒Boolean)(body: ⇒Unit): Unit = { + try { + while (condition) { + body + } + } catch { + case ContinueException ⇒ while_c(condition)(body) + case other: Exception ⇒ throw other + } + } var i = -1