liveBook · Manning

Lazy evaluation

As explained in Learn Haskell by Example

Lazy evaluation delays evaluating an expression until its value is required.

Lazy evaluation delays evaluating an expression until its result is required. An unused argument can therefore be discarded without calculating it, even when calculating it would be expensive. section 6.3.3

Discarding an expensive argument

The expression `const 0 (1000 ^ 100000000)` reduces to `0`; `const` returns its first argument, so the huge second argument is never evaluated. In GHCi, binding the large value and passing it to `const` demonstrates the same behavior. section 6.3.3

Laziness can build only the part of a computation that is needed. A ladder-game search constructs graph elements while searching rather than constructing the entire graph first. Lists and user-defined types are lazy by default; a lazy HashMap preserves deferred values. section 6.3.3

Use laziness deliberately:

  • Prefer it when a search or computation can avoid producing unnecessary results. section 6.3.3
  • Do not assume it is always faster: deferred work can create unexpected or catastrophic memory usage. section 6.3.3 section 8.2.1
  • Choose strict alternatives when appropriate, such as strict folds like `foldl'` or the `StrictData` language extension. section 6.3.3 section 8.2.1
ghci> :{
ghci| const :: a -> b -> a
ghci| const x _ = x
ghci| :}
ghci> x = (1000 :: Int)^(100000000 :: Int)
ghci> y = 0 :: Int
ghci> const y x
0

Inspect and run the compact GHCi example showing that an enormous unused argument is never evaluated. section 6.3.3

Folds make laziness visible by building an expression over a data structure before that expression is forced. The choice between `foldr` and strict `foldl'` depends on whether the accumulating function is lazy. section 8.2.1

How Learn Haskell by Example covers it

How deep it goes
Explains forcing, discarded arguments, lazy data structures, performance trade-offs, and strict alternatives without detailing runtime implementation.
Examples
Demonstrates `const` with an enormous integer, incremental ladder-game graph construction, and lazy versus strict folds.
What you can do after
Evaluate when laziness avoids work, select lazy structures for searches, and diagnose memory risks using strict folds or StrictData.
How it connects
Connects deferred computation with strict evaluation, graph search, hash maps, folds, and memory management.

Also explained in

Compare how 13 books explain lazy evaluation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.