Call-with-current-continuation

From Wikipedia, the free encyclopedia

Call-with-current-continuation is a control function in Scheme and several other programming languages that takes a function f as its only argument and calls f, passing it the current continuation as an argument. Call-with-current-continuation is commonly abbreviated call/cc, and although the Scheme standard does not specify this abbreviation, many implementations provide it.

The continuation behaves like an ordinary function, except that it does not return inside the caller; instead, control flow continues after the call to call/cc. Thus if, for example, the final result is to print the value returned by call/cc, then anything passed to the continuation will be printed.

Call/cc can be used to simulate a return keyword, which is missing from Scheme. E.g.,

 (define (f return)
   (return 1)
   3)

 (display (call-with-current-continuation f))

Calling f with a regular function argument first applies this function to the value 1, then returns 3. However, when f is passed to call/cc (as in the last line of the example), applying the parameter (the continuation) to 1 forces execution the program to jump to the point where call/cc was called and causes call/cc to return the value 1. This is then printed by the display function.

The power of call/cc lies in the ability for the continuation to be called more than once and even from outside the lexical context of the call/cc construction: there are no rules stating that the continuation has to "stay inside" call/cc. The programmer can return as many times as he likes. There are cases in which the function called by call/cc never applies the continuation to anything: in these cases, call/cc usually returns whatever this function did.

Call/cc has been used for several practical purposes, such as implementing amb, an operator which emulates Prolog-style backtracking. Call/cc has also been used to create an exception system in Scheme, as R5RS does not specify one built in. Another use of call/cc is the creation of coroutines, employing call/cc to jump back and forth between coroutines. Similarly, call/cc can help implement Python-like generators.

Call-with-current-continuation has been criticized, especially by Lisp users, as being an unnecessarily complicated and difficult-to-implement means for doing the above things. Critics hold that each one of those tasks can and should be implemented without call/cc, and doing so will make things faster and more efficient. Indeed, in many implementations of Scheme, call/cc is rather slow. To have a speedy call/cc, the operator often needs to be central in design by, for example, using continuation passing style in an intermediate stage of the compiler.

[edit] See also

This article was originally based on material from the Free On-line Dictionary of Computing, which is licensed under the GFDL.