Lazy Evaluation

Suppose we are coding a simple Java program:

Untitled

In the calculateAll method, we can see that what has the highest complexity is calculating the variables, so we can extract this knowledge into a helper function:

Untitled

Note that here a may not be used! Whether we use it or not depends on the boolean extraHard, so we update the code avoiding unused variables:

Untitled

But, can we do this without involving the programmer?

Lazy Evaluation means that we only evaluate the stuff that we need, skipping everything else. In other words, only interpret something when we really need to.

Functions allow us to delay doing stuff, so we can probably use functions or something similar to do lazy execution!

For example, what happens if we call ones.head where:

Untitled

We eagerly call ones, so we will call it recursively until the end of time… or memory. A stack overflow exception will be thrown.

This happens because Scala by default is an eager language. Scala will try to fully evaluate the ones on the right expression, which is not possible. Scala by default does not do lazy evaluation, as this is only possible when there are no side effects. However, Scala does have side effects: you can update variables, etc.

Instead, with:

Untitled

Calling ones.head will return [].

We can call the tail of a lazy list, for example unos.tail.head in:

Untitled