15-150: Principles of Functional Programming

Lecture 12: Continuations

Continuations act as "functional accumulators". The basic idea is to implement a function f by defining a function f' that takes an additional argument, called the continuation. This continuation is a function; it encapsulates the computation that should be done on the result of f. In the base case, instead of returning a result, one calls the continuation. In the recursive case, one augments the given continuation with whatever computation should be done on the result.   (Note: In continuation-passing style code, one requires that f' be tail recursive.)

Continuations can be used to advantage for programming solutions to a variety of problems. In today's lecture we looked at four examples. First, as an introduction, we showed how to model arithmetic operations with continuations. Next, we implemented a function for summing the integers in a list using continuations (and compared that to other possible implementations). Subsequently, we looked at an example in which continuations could be used to efficiently manage evaluations, short-circuiting unnecessary computations (specifically, we wrote a function to compare a list against the inorder traversal of a tree and stopped the comparison as soon as there was a mismatch). Finally, we introduced continuations as a means for doing backtracking search, using both a success continuation and a failure continuation.

Key Concepts

Sample Code

Evaluation trace for the CPS function csum discussed in lecture

Some Notes on Continuations

Additional Notes on Continuations

Slides from Lecture