#MonthOfCode - Day 14: loop

My entry for the 14th day of the month of code. The theme for today is: loop.

Today’s code illustrates Scala’s abilities to define new control structures.

Code after the break.

You know the while loop. It executes some code while a condition is true:

1
2
3
while (condition) {
body
}

Let’s create a while_growing control structure that executes code as long as the “condition” return growing integers:

1
2
3
while_growing (integer_function) {
body
}

To create this new control structure, we define a while_growing function that takes two blocks of code: an integer function and a generic block of code. Then, we execute the block and check if the integers returned by the function are growing.

loop.scalaview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// define the new control structure (a simple function)
def while_growing (f: => Int) (body: => Unit) = {
var value = f // f is executed
var oldValue = 0
do {
body // body is executed
oldValue = value
value = f // f is executed
} while (value > oldValue)
}

// test it!
var x = 0
while_growing ( -(x-3)*(x-3) ) {
x = x + 1
println(x, -(x-3)*(x-3) )
}

Output:

1
2
3
4
5
% scala loop.scala
(1,-4)
(2,-1)
(3,0)
(4,-1)

As soon as the function decreases, the loop stops.

You can try this code by running scala loop.scala or by copy-pasting it on Simply Scala.