Continuation Passing Style
Making the Rest of a Computation Explicit
Continuation Passing Style makes the next action in a program visible as a function argument. You encounter it when studying program transformations and how programming languages represent control flow. Instead of focusing only on the value a function produces, you also describe what should happen to that value. The examples below use synchronous Python functions and ordinary integer arithmetic.
Make the remaining work explicit
A continuation is a function representing the work that remains after a computation produces a value. If an expression computes 2 * bump(x), the work waiting for the result of bump(x) is to multiply that result by two. A function such as lambda y: 2 * y represents that waiting work. In Python, lambda lets you write this small function where it is needed.
Continuation Passing Style, abbreviated CPS, is a way of writing functions that receive an explicit continuation and deliver their computed value by calling it. For a pure function that terminates normally, the central correctness relationship is
The equality describes the required result; it does not prescribe computing f(x) first inside the transformed implementation. Instead, the transformed function arranges its own computations so that their completed value reaches k.
Feature | Direct style | Continuation Passing Style |
|---|---|---|
Function interface | Receives the original inputs | Also receives a continuation |
Delivery of the computed value | Returns it to the caller | Supplies it to the continuation |
Remaining work | Appears around the function call | Appears inside the supplied continuation |
Build one result handoff
Consider a helper that adds two and a surrounding computation that doubles its result:
def bump(x):
return x + 2
def twice_bumped(x):
return 2 * bump(x)The CPS versions make the waiting multiplication explicit:
def bump_cps(x, k):
return k(x + 2)
def twice_bumped_cps(x, k):
return bump_cps(x, lambda y: k(2 * y))The helper supplies its result to the new continuation. That continuation multiplies the received value by two and then supplies the product to the original k. Preserve the original order of operations when building the continuation. Moving the multiplication before the addition would change the computation.
Example: Calling twice_bumped_cps(x, lambda result: result) produces the same integer as twice_bumped(x). The supplied function returns its input unchanged. A different final continuation could turn that integer into a string or perform another calculation. The CPS computation therefore separates producing its value from deciding how the surrounding program uses it.
Tail calls and correctness
In the transformed code, each function call transfers control without leaving further work in its current function. Such a call occupies tail position. Although Python spells the handoff return k(value), there is no arithmetic left after k completes.
Compare this with return k(value) + 2. Here the function waits for k to return and then adds two. The continuation call is therefore not in tail position. Adding a parameter named k does not, by itself, produce CPS.
CPS makes control explicit; its memory behavior also depends on the implementation. Proper tail-call support can avoid accumulating ordinary call frames, but saved continuations can still require storage. CPython does not optimize tail calls between Python functions, so these examples illustrate the transformation without promising constant stack usage.
What to remember
- A continuation represents the remaining computation.
- A CPS function delivers its value by calling the supplied continuation.
- Put pending operations inside new continuations in the correct order.
- Check both the delivered value and whether function calls leave work behind.
Example: Delivering a Ticket Order Total
A ticket-order program charges 240 cents per ticket and adds a fixed delivery charge of 150 cents per order. All amounts are exact, and there are no other charges. The programmer wants the billing calculation to deliver its total to a supplied function rather than decide how the caller will use it.
The terminal continuation is the continuation supplied by the outermost caller to consume the completed result. In this example, it will either return the total unchanged or convert it to dollars.
def ticket_cost_cps(n, k):
return k(240 * n)a) Write order_total_cps(n, k) so that it uses ticket_cost_cps and delivers the complete total, including delivery, to k.
First identify the unfinished work: after the ticket subtotal is available, add the delivery charge and pass the complete total to k. Name the received subtotal ________. The continuation is lambda subtotal: k(subtotal + 150).
def order_total_cps(n, k):
return ticket_cost_cps(
n,
lambda subtotal: k(subtotal + 150)
)The helper call is the final action of order_total_cps. Inside the new continuation, the addition occurs before calling k. The caller's continuation receives the complete order total. This implementation is the required CPS function.
b) Evaluate order_total_cps(3, lambda total: total). State the returned amount in cents.
First calculate the ticket subtotal. Three tickets produce ________ because
Next, the helper invokes the continuation created inside order_total_cps. That continuation adds the fixed delivery charge:
Finally, the terminal continuation lambda total: total receives 870 and returns it unchanged. The expression therefore returns 870 cents. This includes one delivery charge for the order, rather than one per ticket.
c) Replace the terminal continuation so that the same three-ticket order returns its total in dollars. State the result to two decimal places.
The billing functions still calculate and deliver cents. Only the terminal continuation needs to change. The conversion factor is ________, so divide the received numeric value by 100:
order_total_cps(3, lambda total: total / 100)The ticket subtotal remains 720 cents, and adding delivery still produces ________. The terminal continuation then converts the completed amount:
The returned value is 8.70 dollars, expressed to two decimal places. Converting after the complete total is delivered keeps the billing operations in consistent units.
A function written in continuation-passing style takes one extra argument. Instead of returning its result to its caller, it passes that result on. Complete the three statements about this style of programming.
The extra argument is called the , and it represents the rest of the computation that will use the result. The call that hands the result to that argument sits in position, so the function does no further work of its own after making it. Pending work that a direct-style program would keep in stack frames is captured instead by a function value that remembers variables from the scope where it was created, known as a .
A data-processing program uses the following synchronous Python functions. What integer does the final expression return? All values are dimensionless. Give your answer as an exact integer, with zero decimal places.
def scale_cps(x, k):
return k(5 * x)
def report_cps(x, k):
return scale_cps(x, lambda v: k(v - 8))
report_cps(7, lambda r: 2 * r + 1)