Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ben's solution #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/main/scala/internal/ForLoop.scala
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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) {
Expand Down
6 changes: 5 additions & 1 deletion src/main/scala/internal/LoopUntil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
24 changes: 22 additions & 2 deletions src/main/scala/internal/RepeatUntil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

15 changes: 14 additions & 1 deletion src/main/scala/internal/WhileContinue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down