liveBook · Manning

Eager evaluation

As explained in Functional Programming in Scala, Second Edition

Strict code evaluates an argument or expression before the surrounding computation proceeds, rather than delaying evaluation until its value is needed.

Eager evaluation computes an argument or expression before the surrounding computation proceeds. A strict function always evaluates its arguments, so square(41.0 + 1.0) receives 42.0; square(sys.error("failure")) raises an exception before square runs. section 5.1

The contrast with nonstrict evaluation makes the boundary visible. Short-circuiting &&, ||, and if avoid evaluating unused branches, while an ordinary variadic apply evaluates each supplied expression before its body constructs a LazyList. Delaying evaluation requires by-name parameters or thunks; without memoization, forcing the same delayed expression can recompute it. section 5.1 section 5.2.1

An eager argument fails before the function body

def square(x: Double): Double = x * x square(sys.error("failure")) The error is raised while evaluating the argument, before square can execute. By contrast, if2(false, sys.error("fail"), 3) can return 3 when its branches are by-name parameters.

def apply[A](as: A*): LazyList[A] =
  if as.isEmpty then empty
  else cons(as.head, apply(as.tail*))

Inspect how a variadic LazyList constructor eagerly receives its elements before recursively building the result. section 5.2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines strict argument evaluation and demonstrates its timing, but defers broader implementation details to nonstrictness and laziness.
Examples
Uses square, sys.error, conditional branches, short-circuiting operators, and LazyList construction to expose evaluation timing.
What it assumes
Assumes basic Scala function calls and expressions while establishing strictness and nonstrictness from concrete examples.
What you can do after
Evaluate Scala calls by predicting which arguments run before function bodies and which expressions can be skipped.
How it connects
Connects strictness with nonstrictness, by-name parameters, thunks, LazyList, short-circuiting, and memoization.

Also explained in

Compare how 5 books explain eager evaluation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.