Skip to content

Loops (for, while)

Rohit edited this page Jan 6, 2017 · 2 revisions

With states, we transitioned from pure functional programming to combination of functional and imperative programming.

One feature often associated with imperative programming are loops.Turns out that loops, as a feature are nonessential for imperative languages. With just variables we can already model all imperative programs.A loop can be emulated by using a function.

while loop

while(condition){
   statement(s);
}
  • Note: The condition and the command must be passed by name so that they are reevaluated in each iteration.
  • Note: while is tail recursive, so it can operate with a constant stack size.

for loop

In Scala there is a kind of for loop similar to Java’s extended for loop:

for (i <- 1 until 3) { 
    System.out.print(i + " ") 
}

The classical for loop in Java can not be modeled simply by a higher-order function. The reason is that in a Java program like:

for (int i = 1; i < 3; i = i + 1) { 
    System.out.print(i + " "); 
}

the arguments of for contain the declaration of the variable i (int i = 1), which is visible in other arguments and in the body.

for-expressions vs for-Loops

for-loops translate similarly to for-expressions, but using the foreach combinator instead of map and flatMap.

foreach is defined on collections with elements of type T as follows:

def foreach(f: T => Unit): Unit =
// apply ‘f‘ to each element of the collection

Example

for (i <- 1 until 3; j <- "abc") println(i + " " + j)

translates to:

(1 until 3) foreach (i => "abc" foreach (j => println(i + " " + j)))

output:

1a
1b
1c
2a
2b
2c
Clone this wiki locally