liveBook · Manning

Lazy list

As explained in Functional Programming in Scala, Second Edition

A lazy list is an immutable sequence whose elements and continuation are evaluated on demand, allowing finite or infinite sequences.

A lazy list is an immutable sequence whose elements and continuation are evaluated on demand. Unlike a strict List, it can represent finite or infinite sequences while avoiding work that the consumer never requests. section 5.0 section 5.2

Delayed construction

A minimal representation has Empty and Cons cases. Cons stores explicit thunks for both the head and tail: `Cons(() => head, () => tail)`. A `cons` helper preserves by-name arguments in lazy values, so examining the head need not evaluate the tail. `headOption` forces only the head required to produce its result. section 5.2

Laziness also supports compositional efficiency. Chaining `map`, `filter`, and related transformations can fuse into a single demand-driven traversal instead of allocating an intermediate list for every operation. The same structure therefore supports high-level composition and potentially unbounded computation. section 5.0 section 5.2

Useful operations expose only as much computation as the consumer requests:

  • `take` returns a lazy prefix without forcing the unused remainder; `drop` skips elements without forcing the elements discarded; `takeWhile` stops at the first failing predicate. section 5.2.2 section 5.6
  • `toList` forces the entire structure, making finite lazy lists inspectable; a tail-recursive implementation provides stack-safe conversion. section 5.6
  • `from`, `continually`, and Fibonacci generators demonstrate infinite sequences, while `unfold` generalizes generation from an explicit state transition. section 5.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains thunk-based representation, selective forcing, stack safety, core operations, and stateful generation.
Examples
Demonstrates finite prefixes, infinite integer and constant streams, Fibonacci numbers, transformation chains, and REPL conversion with toList.
What it assumes
Assumes recursive immutable lists and higher-order operations while developing strictness, nonstrictness, and delayed evaluation through examples.
What you can do after
Build it from scratch using Scala thunks, lazy constructors, recursive operations, and unfold-based generators.
How it connects
Connects laziness with strictness, immutable data structures, higher-order functions, foldRight, and unfold.

Also explained in

Compare how 2 books explain lazy list →

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.