Programming Search⌘K

Conceptadvanced

Thunk

Also called suspended computation, delayed computation, promise (Scheme), delay and force, suspension.

A thunk is a suspended computation: code with no parameters that computes a value when a program forces it. Thunks implement call by name, call by need and lazy values.

Applies to
core-languages

Idea

A thunk is a computation that has not run yet. It is a small piece of code with no parameters, together with the variables that the code needs. A program creates the thunk at one point and runs it later, when it needs the value. Running a thunk is called forcing it. If the thunk stores its result after the first force, later forces return the stored value:

class Thunk:
    def __init__(self, compute):
        self.compute = compute
        self.done = False
        self.value = None

    def force(self):
        if not self.done:
            self.value = self.compute()
            self.done = True
            self.compute = None
        return self.value


def slow_square(n):
    print("computing", n, "squared")
    return n * n


answer = Thunk(lambda: slow_square(12))
print("thunk created")
print(answer.force())
print(answer.force())
Output
thunk created
computing 12 squared
144
144

The lambda is the suspended computation. Thunk adds the stored result, so slow_square runs one time. Thunks are the machinery under lazy evaluation, call by name and lazy values.

How it works

Delay packages an expression. SICP builds its streams from two operations, delay and force. It states that delay "must package an expression so that it can be evaluated later on demand, and we can accomplish this simply by treating the expression as the body of a procedure."1 So (delay <exp>) can be the same as (lambda () <exp>), and force calls that procedure. In any language with closures, a function with no parameters is a thunk: the closure keeps the variables of the expression alive until the force.

Force with or without memory. A plain thunk runs its code at each force. SICP adds memoization: "the first time they are forced, they store the value that is computed. Subsequent forcings will simply return the stored value without repeating the computation."1 The book connects the two forms to two parameter modes: "The Algol community would refer to our original delayed objects as call-by-name thunks and to the optimized versions as call-by-need thunks."1

The state of a memoized thunk. A memoized thunk has two states. Before the force, it holds code and an environment. After the force, it holds a value, and it can drop the code and the environment, so that the garbage collector can free the objects that only the computation needed. The example above sets compute to None for this reason. An implementation of a lazy language often overwrites the thunk object in place with its value, so every reference to the thunk sees the value. Wikipedia notes that compilers for lazy languages, "such as the Glasgow Haskell Compiler, have relied heavily on thunks, with the added feature that the thunks save their initial result so that they can avoid recalculating it".2

Thunks for parameters. Call by name passes an argument without evaluating it. The Algol 60 report defines it as text replacement: the formal parameter "is replaced, throughout the procedure body, by the corresponding actual parameter".3 A compiler cannot copy the text of the argument into the procedure for every call, so it passes a thunk instead: a routine that computes the argument in the environment of the caller. Wikipedia describes the step: "the compiler can generate a helper subroutine, called a thunk, that calculates the value of the argument."2

Thunks in the language. Scheme has thunks as a built-in feature. The R7RS report states that delay "is used together with the procedure force to implement lazy evaluation or call by need", and that the value of a promise "must be cached" so that "if it is forced a second time, the previously computed value is returned."4 In Haskell, "a function argument is evaluated only when required", so an implementation passes thunks, and seq forces a value.5

In languages

LanguageVerdictNote
PythonIdiom
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptIdiom
TypeScriptIdiom
GoStandard library
RustStandard library
KotlinStandard libraryA value of type () -> T is a plain thunk, and the lazy function returns a memoized, thread-safe thunk for a property; no example file because kotlinc is not installed on the machine that records the examples.
SQLDoes not applySQL has no values that hold code.
BashIdiom
PowerShellIdiomA script block is a plain thunk that the & operator forces; no example file because pwsh is not installed on the machine that records the examples.
HTMLDoes not applyHTML has no evaluation of expressions.
CSSDoes not applyCSS has no evaluation of expressions of this kind.
Regular expressionsDoes not applyA regular expression has no values that hold code.
Language Verdict Plain thunk Memoized thunk
Python idiom lambda: expr a class, or functools.cached_property on an attribute
JavaScript idiom () => expr a closure with a flag
TypeScript idiom () => T a closure with a flag
Java stdlib Supplier<T> a Supplier wrapper, or a holder class
Kotlin stdlib () -> T lazy { }
C# stdlib Func<T> Lazy<T>
Go stdlib func() T sync.OnceValue
Rust stdlib a closure, impl Fn() -> T LazyCell, LazyLock
C idiom a function pointer and a context pointer a struct with a flag
C++ stdlib a lambda, std::function<T()> a lambda with std::optional
Bash idiom a function name or a string for eval a variable that a function fills once
Haskell native every unevaluated expression every unevaluated expression
Scheme native (lambda () expr) delay and force

Java. Supplier<T> "Represents a supplier of results", and the documentation states that there is "no requirement" that each call returns a distinct result.6 So a Supplier is a plain thunk, and memoization is the job of the program.

C#. Func<T> is a plain thunk, and Lazy<T> is a memoized one. Lazy<T> also stores an error: if the factory "throws an exception the first time a thread tries to access the Value property of the Lazy object, the same exception is thrown on every subsequent attempt."7

Go. sync.OnceValue "returns a function that invokes f only once and returns the value returned by f. The returned function may be called concurrently."8

Rust. A closure with no parameters is a plain thunk. LazyCell is "A value which is initialized on the first access."9 LazyLock is the form that threads can share.

PythonGitHub
from functools import cache


def load():
    print("loading")
    return [1, 2, 3]


plain = lambda: load()
memo = cache(load)

print(len(plain()), len(plain()))
print(len(memo()), len(memo()))
Output
loading
loading
3 3
loading
3 3
  • Verdict: idiom. A lambda with no parameters is a plain thunk: each call runs load again.
  • functools.cache on a function with no parameters gives a memoized thunk. The first call runs load, and later calls return the stored list.
  • functools.cached_property is the memoized thunk for one attribute of an object.
#include <functional>
#include <iostream>
#include <optional>
#include <utility>

template <typename T>
class Lazy {
public:
    explicit Lazy(std::function<T()> compute) : compute_(std::move(compute)) {}

    const T& get() {
        if (!value_) {
            value_ = compute_();
            compute_ = nullptr;
        }
        return *value_;
    }

private:
    std::function<T()> compute_;
    std::optional<T> value_;
};

int load() {
    std::cout << "loading\n";
    return 21;
}

int main() {
    auto plain = [] { return load(); };
    std::cout << plain() + plain() << '\n';

    Lazy<int> memo(load);
    std::cout << memo.get() + memo.get() << '\n';
}
Output
loading
loading
42
loading
42
  • Verdict: stdlib. A lambda with no parameters, or a std::function<T()>, is a plain thunk. Lazy stores the result in a std::optional and releases the function after the first force.
  • A function-local static variable is a thread-safe memoized value: it is initialized the first time control passes through its declaration.
JavaGitHub
import java.util.function.Supplier;

public class Main {
    static final class Memo<T> implements Supplier<T> {
        private Supplier<T> compute;
        private T value;

        Memo(Supplier<T> compute) {
            this.compute = compute;
        }

        @Override
        public T get() {
            if (compute != null) {
                value = compute.get();
                compute = null;
            }
            return value;
        }
    }

    static int load() {
        System.out.println("loading");
        return 21;
    }

    public static void main(String[] args) {
        Supplier<Integer> plain = Main::load;
        Supplier<Integer> memo = new Memo<>(Main::load);
        System.out.println(plain.get() + plain.get());
        System.out.println(memo.get() + memo.get());
    }
}
Output
loading
loading
42
loading
42
  • Verdict: stdlib. Supplier<T> is the standard plain thunk, and its documentation does not promise a stored result. Memo adds the stored result. It is not safe for threads; a shared memoized value needs a lock or the holder class idiom.
#include <stdbool.h>
#include <stdio.h>

struct thunk {
    int (*compute)(const void *context);
    const void *context;
    bool done;
    int value;
};

static int sum(const void *context) {
    const int *items = context;
    puts("summing");
    return items[0] + items[1] + items[2];
}

static int force(struct thunk *t) {
    if (!t->done) {
        t->value = t->compute(t->context);
        t->done = true;
    }
    return t->value;
}

int main(void) {
    static const int items[] = {1, 2, 3};
    struct thunk total = {.compute = sum, .context = items};
    puts("thunk created");
    printf("%d\n", force(&total));
    printf("%d\n", force(&total));
    return 0;
}
Output
thunk created
summing
6
6
  • Verdict: idiom. C has no closures, so a thunk is a function pointer plus a pointer to the data that the function needs. The done flag and value field make it a memoized thunk.
  • The context pointer must stay valid until the force. Here items is static, so it lives for the whole program.
static int Load()
{
    Console.WriteLine("loading");
    return 21;
}

Func<int> plain = Load;
Console.WriteLine(plain() + plain());

var memo = new Lazy<int>(Load);
Console.WriteLine(memo.IsValueCreated);
Console.WriteLine(memo.Value + memo.Value);
Console.WriteLine(memo.IsValueCreated);
Output
loading
loading
42
False
loading
42
True
  • Verdict: stdlib. A Func<T> delegate is a plain thunk. Lazy<T> is a memoized thunk: Value runs the factory on the first access, and IsValueCreated tells if the force has happened. By default it is safe for threads.
JavaScriptGitHub
function lazy(compute) {
  let done = false;
  let value;
  return () => {
    if (!done) {
      value = compute();
      done = true;
      compute = undefined;
    }
    return value;
  };
}

const plain = () => {
  console.log("loading");
  return 21;
};
const memo = lazy(plain);

console.log(plain() + plain());
console.log(memo() + memo());
Output
loading
loading
42
loading
42
  • Verdict: idiom. An arrow function with no parameters is a plain thunk. lazy wraps it in a closure that stores the result and drops compute, so the garbage collector can free what the computation captured.
  • A getter that replaces itself with a data property on first access is the usual memoized property.
TypeScriptGitHub
type Thunk<T> = () => T;

function lazy<T>(compute: Thunk<T>): Thunk<T> {
  let state: { done: false; compute: Thunk<T> } | { done: true; value: T } = { done: false, compute };
  return () => {
    if (!state.done) {
      state = { done: true, value: state.compute() };
    }
    return state.value;
  };
}

let calls = 0;
const total: Thunk<number> = lazy(() => {
  calls += 1;
  return [1, 2, 3].reduce((a, b) => a + b, 0);
});

console.log(total(), total(), calls);
Output
6 6 1
  • Verdict: idiom. The type () => T is a plain thunk. The union type of state makes the two states of a memoized thunk explicit: before the force it holds code, and after the force it holds a value.
package main

import (
	"fmt"
	"sync"
)

func load() int {
	fmt.Println("loading")
	return 21
}

func main() {
	plain := func() int { return load() }
	memo := sync.OnceValue(load)

	fmt.Println(plain() + plain())
	fmt.Println(memo() + memo())
}
Output
loading
loading
42
loading
42
  • Verdict: stdlib. A func() T value is a plain thunk. sync.OnceValue turns it into a memoized thunk that many goroutines can call at the same time, and sync.OnceValues does the same for a function that returns a value and an error.
RustGitHub
use std::cell::LazyCell;

fn load() -> i32 {
    println!("loading");
    21
}

fn main() {
    let plain = || load();
    println!("{}", plain() + plain());

    let memo = LazyCell::new(load);
    println!("{}", *memo + *memo);
}
Output
loading
loading
42
loading
42
  • Verdict: stdlib. A closure with no parameters is a plain thunk. LazyCell runs its function on the first dereference and stores the value. LazyLock is the form for a value that threads share, such as a static.
BashGitHub
calls=0
total=""

compute_total() {
  calls=$((calls + 1))
  total=42
}

force() {
  "$1"
}

force compute_total
force compute_total
echo "plain: calls=$calls"

calls=0
total=""
force_once() {
  if [[ -z $total ]]; then
    "$1"
  fi
}

force_once compute_total
force_once compute_total
echo "memoized: calls=$calls total=$total"
Output
plain: calls=2
memoized: calls=1 total=42
  • Verdict: idiom. Bash has no closures. The name of a function is the thunk, and "$1" forces it. A global variable that the function fills one time makes it memoized.
  • A force inside a command substitution, such as $(force compute_total), runs in a subshell, so the stored value is lost when the subshell ends.

Call-by-name thunk and call-by-need thunk. The first runs at each force, so its side effects happen at each force. The second runs at most one time. Most library types for laziness are call-by-need thunks.

Promises in Scheme. A Scheme promise is a memoized thunk. R7RS adds delay-force for lazy loops: it lets "iterative lazy algorithms that might result in a long series of chains of delay and force" run without "consuming unbounded space during evaluation."4

Lazy initialization. A memoized thunk stored in a field or a global is lazy initialization: the value is created on the first access. See lazy evaluation.

Streams. A stream is a pair of a value and a thunk for the rest. See lazy sequence and stream.

Other uses of the word. Compilers and linkers also use the word thunk for small generated routines that adjust arguments before they call another routine. Wikipedia lists thunks for multiple inheritance in C++, which adjust the object address, and thunks that connect code with different calling conventions.2 These thunks do not delay anything, but they share the idea of a small helper routine that a tool makes for a call.

Pitfalls

Late binding of captured variables. A thunk captures variables, not values. If the variable changes before the force, the thunk sees the last value:

This code runs but gives a wrong answer on purpose.

thunks = [lambda: n * 10 for n in range(3)]
print([thunk() for thunk in thunks])
Output
[20, 20, 20]

All three lambdas share the one variable n, and the loop has ended at 2 when they run. Bind the value when you create the thunk:

thunks = [lambda n=n: n * 10 for n in range(3)]
print([thunk() for thunk in thunks])
Output
[0, 10, 20]

Repeated work in a plain thunk. A thunk without memoization runs its code at each force. If the code is slow or has side effects, they happen again and again. Use a memoized form, or force the thunk one time and keep the value.

Errors at force time. A thunk fails when a program forces it, not when the program creates it. The error can appear far from the code that made the thunk. R7RS states that a delayed expression "is evaluated using the parameter values and exception handler of the call to force which first requested its value".4 Some memoized thunks store the error too, as Lazy<T> and sync.OnceValue do, so a failed thunk fails at each force.

Thunks that hold memory. An unforced thunk keeps its environment alive. A long chain of unforced thunks can hold much more memory than the value that it describes. This is a space leak.

Threads. Two threads can force the same memoized thunk at the same time. A simple flag check can then run the code twice. Use a thread-safe form, such as LazyLock or sync.OnceValue. In .NET, "By default, all public and protected members of the Lazy class are thread safe".7

Cost

A thunk costs a heap allocation for the code pointer and the captured variables. Each force costs a call through a pointer and, for a memoized thunk, a check of the ready flag. A thread-safe memoized thunk also needs an atomic operation or a lock on the first force. These costs are small for a single lazy value and large when a program makes a thunk for each element of a large structure. A lazy language tries to avoid most thunks: when the compiler can prove that a function always needs an argument, it evaluates the argument before the call and makes no thunk.

History

The word comes from the first Algol 60 compilers. Wikipedia states that "The term originated as a whimsical irregular form of the verb think", and that it refers to the analysis that the compilers needed "to determine what type of routine to generate."2 Peter Ingerman described the method in "Thunks: a way of compiling procedure statements with some comments on procedure declarations", in Communications of the ACM in January 1961.2 Later, SICP noted that "Delayed evaluation, which is the key to making streams practical, was inherent in Algol 60's call-by-name parameter-passing method."1 Scheme made delay and force part of the language, and compilers for lazy languages such as Haskell came to rely on thunks for every unevaluated expression.2 Eager languages give thunks as library types, such as Supplier<T> in Java and Lazy<T> in .NET.67

References

  1. Structure and Interpretation of Computer Programs, H. Abelson and G. J. Sussman, second edition, MIT Press, 3.5.1 Streams Are Delayed Lists, Implementing delay and force; footnote 58
  2. Thunk, Wikipedia, introduction; Background; Applications, Functional programming; references 1 and 2
  3. Revised Report on the Algorithmic Language Algol 60, P. Naur, editor, 4.7.3.2 Name replacement (call by name)
  4. Revised7 Report on the Algorithmic Language Scheme, 4.2.5 Delayed evaluation
  5. Haskell 2010 Language Report, Predefined Types and Classes, 6.2 Strict Evaluation
  6. Interface Supplier, Java SE 25 API documentation, description
  7. Lazy<T> Class, .NET API documentation, Remarks, Exception caching
  8. sync package, Go standard library, func OnceValue
  9. LazyCell, Rust standard library, description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/82JJDC/text.yaml