- Courses
- 💻Programming Languages
- 🐫OCaml (WIP)
- Functional Design Idioms
- Lazy Evaluation & Streamed Data
On this page
Lazy Evaluation (Lazy Module) and Infinite/Streamed Data
Published on August 8, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
OCaml evaluates eagerly by default: a let binding computes its value immediately, whether or not that value ever actually gets used. The Lazy module offers an alternative — a computation that's deferred until something explicitly demands its result, and then remembered afterward so it's never repeated. This single mechanism is also what makes it possible to represent genuinely infinite data as an ordinary value, generating each piece only as something actually asks for it.
Deferring a Computation With lazy
Wrapping an expression in lazy doesn't run it — it packages the computation up, unevaluated, as a value of type 'a Lazy.t:
# let x = lazy (print_endline "computing..."; 42);;
val x : int Lazy.t = <lazy>
Nothing was printed by this binding, because nothing has demanded x's value yet. Lazy.force is what actually triggers the computation:
# Lazy.force x;;
computing...
- : int = 42
Forcing Twice Doesn't Recompute
The genuinely useful part of Lazy.t is that its result is memoized: forcing the same lazy value a second time returns the cached result directly, without running the computation again.
# Lazy.force x;;
- : int = 42
Notice "computing..." isn't printed the second time — x already knows its own result from the first force, and simply hands it back. This matters most for expensive computations that might reasonably be forced more than once over a program's lifetime: the cost is paid exactly once, no matter how many times the result is actually needed afterward.
A Boundary Case Worth Knowing
Forcing a lazy value that tries to force itself in the middle of its own computation — directly or through a cycle — raises Lazy.Undefined rather than looping forever or producing a nonsensical result; the same exception is raised if a suspension is forced concurrently from more than one thread, fiber, or domain at once. Self-referential lazy definitions like let rec x = lazy x are rejected outright by the type checker under ordinary compilation, and only become accepted (producing exactly this kind of ill-founded value) under the specific -rectypes compiler option, which is not part of everyday OCaml usage.
Building an Infinite List by Hand
Laziness is what makes an infinite data structure representable at all: as long as only the next piece needs to exist at any given moment, the rest of an infinite structure can stay unevaluated indefinitely. A lazy list — sometimes called a stream — captures this directly by making its tail a lazy value instead of an ordinary one:
type 'a lazy_list = Cons of 'a * 'a lazy_list Lazy.t
let rec naturals_from n = Cons (n, lazy (naturals_from (n + 1)))
let naturals = naturals_from 0
naturals is a value that, in principle, represents every natural number — but constructing it doesn't loop forever, since naturals_from (n + 1) inside the lazy block is never actually run until something forces it. A function that pulls a finite prefix out of an infinite lazy list only forces exactly as many tails as it actually needs:
let rec take n (Cons (x, rest)) =
if n = 0 then []
else x :: take (n - 1) (Lazy.force rest)
# take 5 naturals;;
- : int list = [0; 1; 2; 3; 4]
take 5 naturals only ever forces the first five tails of an infinite structure — the rest of naturals remains just as unevaluated after this call as it was before.
The Standard Library's Seq Module
Hand-rolling a lazy list is instructive, but OCaml's standard library already provides a general-purpose version of the same idea: Seq.t. Its definition is built from plain functions rather than Lazy.t values directly:
type 'a node = Nil | Cons of 'a * 'a t
and 'a t = unit -> 'a node
A 'a Seq.t is a function that, when called, produces either Nil (the sequence is empty) or Cons of an element and the rest of the sequence, itself another such function. Wrapping the "next step" in a plain unit -> ... function, rather than a Lazy.t, is what lets a sequence represent something open-ended, generated on demand:
let rec naturals_from n () = Seq.Cons (n, naturals_from (n + 1))
let naturals = naturals_from 0
# naturals |> Seq.take 5 |> List.of_seq;;
- : int list = [0; 1; 2; 3; 4]
Seq.map, Seq.filter, and similar transformations are lazy in exactly the same sense: calling Seq.map f seq doesn't apply f to anything immediately — it builds a new sequence that applies f only as each element is actually traversed, which is precisely what allows these transformations to be chained together and still work correctly on an infinite sequence, as long as something downstream eventually stops asking for more elements.
A Sharp Difference From Lazy.t: No Automatic Memoization
Here's a detail worth being precise about, since it's easy to assume Seq.t behaves exactly like a chain of Lazy.t values: it doesn't. A sequence's nodes are delayed behind an ordinary closure, not a Lazy.t block, which means a sequence built around a side effect can recompute that side effect every single time it's traversed, unlike a genuine Lazy.t, which always caches after its first force.
let noisy = Seq.map (fun x -> print_endline "computing"; x * 2) naturals
Traversing noisy twice runs "computing" again in full on the second traversal — nothing about Seq.t remembers the first traversal's results by default. When that recomputation is genuinely undesirable, Seq.memoize wraps a sequence so that each node, once computed, is cached using an actual Lazy.t suspension underneath — at the cost of no longer being safe to traverse from multiple threads or domains concurrently, since those underlying suspensions aren't thread-safe. Seq.once offers the opposite guarantee in the other direction: it wraps a sequence so that traversing it — or any suffix of it — more than a single time raises an exception, which is useful for representing a genuinely one-shot resource, like reading from an input channel, where re-traversal wouldn't even make sense.
Running Forever Without Leaking Memory
Because a sequence's later elements simply don't exist until something asks for them, an infinite sequence can be iterated over indefinitely using only constant memory — nothing about the sequence's "unconsumed remainder" is being stored anywhere, since it's just a function waiting to be called:
let () = Seq.iter (fun n -> Printf.printf "%d\n%!" n) naturals
Running this prints an endless stream of increasing integers and never terminates on its own, but it does so in constant space — the program doesn't accumulate memory as it runs, since each number is produced, printed, and discarded before the next one is generated. This is a direct, practical demonstration of what laziness actually buys: a program can work with a conceptually unbounded stream of data without ever needing to hold more than the current piece of it in memory at once.
When Laziness Is Genuinely the Right Tool
Laziness earns its place in three recurring situations: avoiding a computation that might turn out to be unnecessary, such as an expensive default value only needed when nothing else was supplied; representing data that's naturally unbounded or open-ended, like an infinite numeric sequence or a stream of incoming events; and decoupling how much of something gets produced from how much a consumer actually ends up asking for, letting a producer and consumer stay independent of each other's pace. Outside of these situations, eager evaluation remains the simpler default, and reaching for laziness where it isn't actually needed mostly adds a layer of indirection without a corresponding benefit.
Key Takeaways
lazy exprdefers a computation into a value of type'a Lazy.t;Lazy.forcetriggers it, and the result is memoized, so a secondforcereturns the cached value without recomputing.- Forcing a lazy value that tries to force itself, or forcing the same suspension concurrently from multiple threads or domains, raises
Lazy.Undefined. - A lazy list, built with a
Lazy.t-wrapped tail, represents an infinite structure by only ever computing as many tails as are actually forced. Seq.tis the standard library's general-purpose version of this idea, built fromunit -> 'a nodefunctions rather thanLazy.tvalues directly, with transformations likeSeq.mapapplying lazily as a sequence is traversed.- Unlike
Lazy.t, a plainSeq.tdoes not memoize by default — traversing it twice can recompute everything from scratch;Seq.memoizeadds caching, andSeq.onceenforces single-traversal safety instead. - An infinite sequence can be iterated indefinitely in constant space, since only the currently requested element ever needs to exist in memory at once.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Tail Recursion, Accumulators & Stack Safety
Next
Guided Exercise: Build a JSON Parser
- Deferring a Computation With lazy
- Forcing Twice Doesn't Recompute
- A Boundary Case Worth Knowing
- Building an Infinite List by Hand
- The Standard Library's Seq Module
- A Sharp Difference From Lazy.t: No Automatic Memoization
- Running Forever Without Leaking Memory
- When Laziness Is Genuinely the Right Tool
- Key Takeaways
