#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.
You know the while
loop. It executes some code while a condition is true:
1 | while (condition) { |
Let’s create a while_growing
control structure that executes code as long as
the “condition” return growing integers:
1 | while_growing (integer_function) { |
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.
1 | // define the new control structure (a simple function) |
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.