Continuation-passing style
From Free net encyclopedia
Continuation-passing style (CPS) is a term used within functional programming to describe a style of programming wherein control is passed explicitly in the form of a continuation.
Contents |
Introduction
Instead of "returning" values as in the more familiar direct style, a function written in CPS takes an explicit continuation argument which is meant to receive the result of the computation performed within the function. When a subroutine is invoked within a CPS function, the calling function is required to supply a procedure to be invoked with the subroutine's "return" value.
Programs can be automatically transformed from CPS to direct style. Functional and logic compilers often use CPS as an intermediate representation where a compiler for an imperative or procedural programming language might employ static single assignment form (SSA). CPS is used more frequently by compilers than by programmers as a local or global style.
CPS is a monad.
Examples
In the Scheme programming language, the simplest of direct-style functions is the identity function:
(lambda (x) x)
which in CPS becomes:
(lambda (x return) (return x))
where return is the continuation argument (often also called k). A further comparison of direct and CPS style is below.
Direct style | |
---|---|
(define (mysqrt x) (sqrt x)) (display (mysqrt 4)) |
(define (mysqrt x k) (k (sqrt x))) (mysqrt 4 display) |
(+ (mysqrt 4) 2) |
(mysqrt 4 (lambda (x) (+ x 2))) |
(define (factorial n) (if (<= n 1) 1 (* n (factorial (- n 1))))) (+ (factorial 4) 2) |
(define (factorial n k) (if (<= n 1) (k 1) (factorial (- n 1) (lambda (ret) (k (* n ret)))))) (factorial 4 (lambda (x) (+ x 2))) |
The translations shown above show that CPS is a global transformation; the direct-style factorial takes, as might be expected, a single argument. The CPS factorial takes two: the argument and a continuation. Any function calling a CPS-ed function must either provide a new continuation or pass its own; any calls from a CPS-ed function to a non-CPS function will use implicit continuations. Thus, to ensure the total absence of a function stack, the entire program must be in CPS.
As an exception, mysqrt calls sqrt without a continuation — here sqrt is considered a primitive operator; that is, it is assumed that sqrt will compute its result in finite time and without abusing the stack. Operations considered primitive for CPS tend to be arithmetic, constructors, accessors, or mutators; any O(1) operation will be considered primitive.
CPS-type programming is also useful when the calling function does not want to wait until the called function completes. For example, in user-interface (UI) programming, a routine can set up dialog box fields and pass these, along with a continuation function, to the UI framework. This call returns right away, allowing the application code to continue while the user interacts with the dialog box. Once the user presses the "OK" button, the framework calls the continuation function with the updated fields.
function Confirm_name() { fields.name = name; framework.Show_dialog_box(fields, Confirm_name_continuation); }
function Confirm_name_continuation(fields) { name = fields.name; }
A similar idea can be used when the function must run in a different thread or on a different processor. The framework can execute the called function in a worker thread, then call the continuation function in the original thread with the worker's results. This is in Java using the Swing UI framework:
void buttonHandler() { // This is executing in the Swing UI thread. // We can access UI widgets here to get query parameters. final int parameter = getField(); new Thread(new Runnable() { public void run() { // Now we're in a separate thread. // We can do things like hit a database or access // a blocking resource like the network to get data. final int result = lookup(parameter); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { // Now we're back in the UI thread and can use // the fetched data to fill in UI widgets. setField(result); } }); } }).start(); }
CPS and tail calls
Note that in CPS, there is no implicit continuation — every call is a tail call. There is no "magic" here, as the continuation is simply explicitly passed. Using CPS without tail call optimization (TCO) will cause not only the explicit continuation to grow during recursion, but also the function stack itself.
As CPS and TCO eliminate the concept of an implicit function return, their combined use can eliminate the need for a runtime stack. Several compilers and interpreters for functional programming languages use this ability in novel ways.
Use and implementation
Continuation passing style can be used to implement continuations in a functional language that does not feature first-class continuations but does have first-class functions. Without first-class functions, techniques such as trampolining of thunk closures can be used; in this case, it is possible to convert tail calls into gotos in a loop, eliminating even the need for TCO.
Writing code in CPS, while not impossible, is often error-prone. There are various translations, usually defined as one- or two-pass conversions of pure lambda calculus, which convert direct style expressions into CPS expressions. Writing in trampolined style, however, is extremely difficult; when used, it is usually the target of some sort of transformation, such as compilation.
Use in other fields
Outside of computer science, CPS is of more general interest as an alternative to the conventional method of composing simple expressions into complex expressions. For example, within linguistic semantics, Chris Barker and his collaborators have suggested that specifying the denotations of sentences using CPS might explain certain phenomena in natural language [1].
See also
- Andrew Appel describes the construction of a CPS-based compiler for ML in: Template:Cite book.
- Chicken Scheme compiler, an example of a Scheme compiler that exploits continuation-passing style to translate Scheme procedures into C functions that run using the Scheme heap as their stack.