Chapter 11. Lazy Evaluation

Although laziness is often seen as a character flaw in people, it can be considered a favorable feature in programming languages. In computer science terms, laziness is the antagonist to strictness—or eagerness—of code evaluation.

This chapter will show you how being lazy can improve performance. You will learn about the difference between strict and lazy evaluation and its impact on your code’s design.

Laziness Versus Strictness

The strictness of a language describes the semantics of how your code is evaluated.

Strict evaluation happens as soon as possible, such as declaring or setting a variable or passing an expression as an argument. Non-strict evaluation, however, happens when the result of an expression is actually needed. This way, expressions can have a value even if one or more subexpressions fail to evaluate.

The functional programming language Haskell has non-strict semantics by default, evaluating expressions from the outermost to the inner ones. This allows you to create control structures or infinite data sequences due to the separation of the creation and consumption of expressions.

Let’s take a look at the following strict Java code of a simple method accepting two arguments but using only one for its logic:

int add(int x, int y) {
  return x + x;
}

The non-strict Haskell equivalent function declaration looks more like a variable assignment:

add x y = x + x

This function also uses only its first argument and doesn’t evaluate the second ...

Get A Functional Approach to Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.