Unit content
Continuations and continuation-passing style
A continuation represents “the rest of the computation” from a particular point.
In the expression
$$1 + (2\times 3),$$
while evaluating $2\times3$, the continuation is essentially “take the result and add 1.”
Continuation-passing style (CPS) makes this implicit control state explicit by passing a function that receives the result. Instead of
square(x) = x * x
we can write conceptually
square_cps(x, k) = k(x * x)
where k is the continuation.
A sequence of calls can then be expressed without returning through the ordinary call stack: each computation explicitly invokes the continuation representing what should happen next.
CPS exposes the structure behind callbacks, exceptions, coroutines and other nonlocal control mechanisms. For example, an exception handler can be understood as an alternative continuation selected when normal evaluation cannot proceed.
Transforming a program into CPS also clarifies evaluation order because every intermediate result is named and every next step is explicit. Compilers use related representations because control flow becomes easier to analyze and transform.
Continuations are therefore not only an implementation trick: they are a semantic representation of control itself.