The idea: compute a value only when it is needed, and only once

Most languages are eager (strict): before a function is called, every argument is evaluated to a value. Haskell is lazy. An argument is not evaluated at the call. Instead the program puts a thunk in the heap: a box that holds the unevaluated expression (its code and the variables it uses). The thunk is evaluated only when something needs its value. That moment is called forcing the thunk. After it runs, the box is overwritten with the value (the update), so the work is never done twice.

Three stages of one thunk t1 in the heap. Made: a purple box t1 holding the code 2 + 3, made at the call sq t1. Forced: the box turns orange while 2 + 3 runs, because * needs its left operand. Updated: the box is now a green value 5; the second use of t1 reads 5 with no work.
A thunk is made at the call, forced when a value is needed, then overwritten with the value.

On the canvas, the heap panel shows every thunk as a purple box with a name tag (t1, t2, …). Orange means "being evaluated now", green means a value, and a white : box is a list cell, with its head below it and an arrow to its tail. The program panel shows the expression now and one line per reduction: one rewrite by a function equation (like sq y = y * y) or one primitive step (like 2 + 3 → 5). The counters count the reductions, the thunks made, the times a thunk's code ran (evaluations), and the thunks still waiting.

What forces a thunk

Nothing is evaluated "just because". A thunk is forced only when one of these needs to look inside it:

  • a pattern match: take n (x:xs) must know if the list is [] or a cell x : xs;
  • a primitive like + or * on numbers;
  • print, which must show the result.

Forcing goes only as far as the outermost constructor (the weak head normal form). Forcing [1..] gives one cell 1 : [2..], and the tail [2..] is a new thunk. A pattern that does not look at an argument does not force it: take 0 _ = [] never touches the list.

Sharing: call by need vs call by name

In sq (2 + 3) with sq y = y * y, the body uses y twice. Both uses point to the same thunk t1. The first use forces t1: 2 + 3 → 5, and t1 is overwritten with 5. The second use just reads 5. This is call by need, the strategy of Haskell: 3 reductions (Demo: sq (2 + 3) by need).

Call by name is the same idea without the update. Each use runs the thunk's code again, so 2 + 3 is computed twice: 4 reductions. Eager evaluation computes 2 + 3 once, before the call: 3 reductions and no thunk at all (Demo: sq (2 + 3) by name vs by need).

Two columns for sq t1 with t1 = 2 + 3. By name: sq t1 to t1 * t1; force t1, 2 + 3 to 5; force t1 again, 2 + 3 to 5; 5 * 5 to 25; 4 reductions, t1 ran 2 times. By need: sq t1 to t1 * t1; force t1, 2 + 3 to 5 and t1 is overwritten with 5; read t1 = 5, no work; 5 * 5 to 25; 3 reductions, t1 ran once.
By name runs 2 + 3 twice (4 reductions); by need runs it once and reuses the value (3 reductions).
Strategysq (2 + 3)Thunks2 + 3 computed
eager (call by value)3 reductions0once, before the call
lazy, call by name4 reductions1twice
lazy, call by need3 reductions1once, at the first use

By name and by need always give the same answer in a pure language like Haskell, because evaluating an expression twice gives the same value. Only the work differs. Parameter passing shows by name and by need inside one procedure call of an imperative language, where side effects make them differ.

Infinite lists

Because a list's tail is a thunk, a list can be infinite. [1..] is the list of all positive numbers. take 5 [1..] works like this: take needs the first cell, so it forces [1..], which gives 1 : [2..]. take returns 1 : take 4 [2..], and the rest of its result is again a thunk. print shows 1 and forces that thunk, and so on (Demo: take 5 [1..] lazily).

In the end, print shows [1,2,3,4,5]. The run made 11 thunks: 6 for [1..] … [6..] and 5 for the rest of take's result (take 4 … down to take 0 …). It forced 10 of them, in 11 reductions. The thunk [6..] was made, but it is never forced, because take 0 _ = [] does not look at the list. Under eager evaluation, [1..] must be finished before take starts, and it never finishes. The page stops it after 6 reductions (Demo: take 5 [1..] eagerly never ends).

Less work, or more memory

Laziness can save work. head (map sq [1, 2, 3, 4]) needs only the first square. Lazily, map makes one cell with two thunks, sq 1 and map sq [2,3,4]. head takes the first one, and print forces it: 4 reductions, and the other squares are never computed. Eagerly, map builds the whole list first, with all four squares: 14 reductions for the same answer 1 (Demo: head (map sq …), eager vs lazy work).

Laziness can also cost memory. foldl (+) 0 [1, 2, 3, 4] passes the new accumulator f z x as an argument, so it becomes a thunk at every step. After the list ends, the heap holds a chain of 4 thunks, t4 = t3 + 4, t3 = t2 + 3, t2 = t1 + 2, t1 = 0 + 1, and not one addition has run. Forcing t4 must force t3, which forces t2, which forces t1: the forces nest 4 deep. With a million elements this is a million thunks and a deep stack. The eager version, which is what foldl' from Data.List does, adds at every step and keeps one number. Both take 9 reductions; the difference is the peak of 4 waiting thunks against 0 (Demo: foldl builds a chain of thunks).

Top, lazy foldl (+) 0 [1, 2, 3, 4]: four purple thunks in a row, t1 = 0 + 1, t2 = t1 + 2, t3 = t2 + 3, t4 = t3 + 4, each pointing to the one before; 9 reductions, peak 4 waiting thunks, forcing t4 goes 4 forces deep. Bottom, eager foldl prime: the one accumulator shown over time as acc = 1, acc = 3, acc = 6, acc = 10; 9 reductions, 0 thunks.
Same 9 reductions: lazy foldl keeps a chain of 4 thunks, foldl' keeps one number.
Programeagerlazy (by need)
sq (2 + 3)3 reductions, 0 thunks3 reductions, 1 thunk
take 5 [1..]never ends11 reductions, 11 thunks, 1 never forced
head (map sq [1, 2, 3, 4])14 reductions4 reductions, 3 thunks
foldl (+) 0 [1, 2, 3, 4]9 reductions, 0 thunks9 reductions, 4 thunks waiting at the peak

Asking for strictness

When a thunk chain like the foldl one is a problem, Haskell lets the programmer force values early:

  • seq a b forces a (to weak head normal form), then returns b;
  • f $! x forces x, then calls f;
  • foldl' uses seq on the accumulator at every step;
  • a bang pattern go !acc (x:xs) = … (the BangPatterns extension) forces the argument when the equation matches.

GHC also runs a strictness analysis: when it can prove that a function will always force an argument, it evaluates the argument at the call and skips the thunk. With optimisation on, GHC often turns the foldl example into a plain loop. The page shows the meaning without these optimisations.

See also closures and currying (a thunk is like a closure with no arguments: code plus the environment it needs), map, filter and reduce (foldl is reduce), persistent trees (immutable data that sharing makes cheap) and static vs dynamic scoping.

What the page leaves out

The page counts reductions by hand-chosen rules, and it treats numbers and the input lists as already evaluated. It leaves out how GHC compiles thunks (the STG machine, info tables and blackholing of a thunk under evaluation), garbage collection of thunks nobody points to, strictness analysis and the other optimisations that remove thunks, Integer versus Int, exceptions inside thunks, lazy I/O, and evaluation of a value all the way down (deepseq). Under call by name, a list cell that nobody else needs is drawn in the place of the thunk it came from.

On the mind map

Open the Java & the JVM mind mapJava & the JVMFrom source to bytecode: translate first, or while runningFrom source to bytecodeStartup and class loading: what happens before main()Startup and class loadingJIT compilers: compile hot code using profilesJIT compilersMemory and GC: find and free unreachable objectsMemory and GCCollections: how java.util stores keysCollectionsThreads and memory model: Java threads on real coresThreads and memory modelSpring framework: a container builds your objectsSpring frameworkStack vs heap in JavaStack vs heap in Javaframes on the stack, objects in TLABsException unwindingException unwindingfinally runs; return in finally winsJava GCsJava GCsParallel, G1 regions, ZGC load barriersTracing vs ref countingTracing vs ref countingrefcount frees at once but leaks cyclesPython GCPython GCrefcount plus a cycle collectorGo GCGo GCtri-colour marking with a write barrierPass by value vs referencePass by value vs referenceJava copies the reference, not the objectParameter passing modesParameter passing modesBy name re-evaluates a[i] at every useLazy evaluationThunk runs once, then holds its valueCard table and barriersCard table and barriersold-to-young refs marked dirtySafepointsSafepointsall threads park before a pauseOpen the Java & the JVM mind mapJava & the JVMfind and free unreachable objectsMemory and GCStack vs heap in JavaStack vs heap in Javaframes on the stack, objects in TLABsException unwindingException unwindingfinally runs; return in finally winsJava GCsJava GCsParallel, G1 regions, ZGC load barriersTracing vs ref countingTracing vs ref countingrefcount frees at once but leaks cyclesPython GCPython GCrefcount plus a cycle collectorGo GCGo GCtri-colour marking with a write barrierPass by value vs referencePass by value vs referenceJava copies the reference, not the objectParameter passing modesParameter passing modesBy name re-evaluates a[i] at every useLazy evaluationThunk runs once, then holds its valueCard table and barriersCard table and barriersold-to-young refs marked dirtySafepointsSafepointsall threads park before a pause
This page on the Java & the JVM mind map · 37 pages in 7 branches · open it to see the whole map and test yourself in recall mode.