Continuation Of
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, a continuation is an abstract representation of the
control state Alcoholic beverage control states, generally called control states, less often ABC states, are 17 states in the United States that, as of 2016, have state monopoly over the wholesaling or retailing of some or all categories of alcoholic beverag ...
of a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to execute. Computer programs are one component of software, which also includes documentation and other intangible components. A computer program ...
. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computational process at a given point in the process's execution; the created data structure can be accessed by the programming language, instead of being hidden in the
runtime environment In computer programming, a runtime system or runtime environment is a sub-system that exists both in the computer where a program is created, as well as in the computers where the program is intended to be run. The name comes from the compile t ...
. Continuations are useful for encoding other control mechanisms in programming languages such as exceptions, generators,
coroutine Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
s, and so on. The "current continuation" or "continuation of the computation step" is the continuation that, from the perspective of running code, would be derived from the current point in a program's execution. The term ''continuations'' can also be used to refer to first-class continuations, which are constructs that give a
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
the ability to save the execution state at any point and return to that point at a later point in the program, possibly multiple times.


History

The earliest description of continuations was made by
Adriaan van Wijngaarden Adriaan "Aad" van Wijngaarden (2 November 1916 – 7 February 1987) was a Dutch mathematician and computer scientist. Trained as an engineer, Van Wijngaarden would emphasize and promote the mathematical aspects of computing, first in numerical an ...
in September 1964. Wijngaarden spoke at the IFIP Working Conference on Formal Language Description Languages held in Baden bei Wien, Austria. As part of a formulation for an
Algol 60 ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
preprocessor, he called for a transformation of proper procedures into
continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
, though he did not use this name, and his intention was to simplify a program and thus make its result more clear.
Christopher Strachey Christopher S. Strachey (; 16 November 1916 – 18 May 1975) was a British computer scientist. He was one of the founders of denotational semantics, and a pioneer in programming language design and computer time-sharing.F. J. Corbató, et al., ...
,
Christopher P. Wadsworth Christopher is the English version of a Europe-wide name derived from the Greek name Χριστόφορος (''Christophoros'' or '' Christoforos''). The constituent parts are Χριστός (''Christós''), "Christ" or "Anointed", and φέρει ...
and
John C. Reynolds John Charles Reynolds (June 1, 1935 – April 28, 2013) was an American computer scientist. Education and affiliations John Reynolds studied at Purdue University and then earned a Doctor of Philosophy (Ph.D.) in theoretical physics from Harvard U ...
brought the term ''continuation'' into prominence in their work in the field of
denotational semantics In computer science, denotational semantics (initially known as mathematical semantics or Scott–Strachey semantics) is an approach of formalizing the meanings of programming languages by constructing mathematical objects (called ''denotations'' ...
that makes extensive use of continuations to allow sequential programs to be analysed in terms of
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
semantics. Steve Russell invented the continuation in his second
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
implementation for the
IBM 704 The IBM 704 is a large digital mainframe computer introduced by IBM in 1954. It was the first mass-produced computer with hardware for floating-point arithmetic. The IBM 704 ''Manual of operation'' states: The type 704 Electronic Data-Pro ...
, though he did not name it. gives a complete history of the discovery of continuations.


First-class continuations

First-class continuations are a language's ability to completely control the execution order of instructions. They can be used to jump to a function that produced the call to the current function, or to a function that has previously exited. One can think of a first-class continuation as saving the ''execution'' state of the program. It is important to note that true first-class continuations do not save program data – unlike a
process image In computing, a system image is a serialized copy of the entire state of a computer system stored in some non-volatile form such as a file. A system is said to be capable of using system images if it can be shut down and later restored to exactly ...
– only the execution context. This is illustrated by the "continuation sandwich" description:
''Say you're in the kitchen in front of the refrigerator, thinking about a sandwich. You take a continuation right there and stick it in your pocket. Then you get some turkey and bread out of the refrigerator and make yourself a sandwich, which is now sitting on the counter. You invoke the continuation in your pocket, and you find yourself standing in front of the refrigerator again, thinking about a sandwich. But fortunately, there's a sandwich on the counter, and all the materials used to make it are gone. So you eat it. :-)''
In this description, the sandwich is part of the program ''data'' (e.g., an object on the heap), and rather than calling a "make sandwich" routine and then returning, the person called a "make sandwich with current continuation" routine, which creates the sandwich and then continues where execution left off.
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
was the first full production system (1969-1970), providing first "catch" and then
call/cc In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
. Bruce Duba introduced call/cc into SML. Continuations are also used in models of computation including
denotational semantics In computer science, denotational semantics (initially known as mathematical semantics or Scott–Strachey semantics) is an approach of formalizing the meanings of programming languages by constructing mathematical objects (called ''denotations'' ...
, the
actor model The actor model in computer science is a mathematical model of concurrent computation that treats ''actor'' as the universal primitive of concurrent computation. In response to a message it receives, an actor can: make local decisions, create more ...
,
process calculi In computer science, the process calculi (or process algebras) are a diverse family of related approaches for formally modelling concurrent systems. Process calculi provide a tool for the high-level description of interactions, communications, and ...
, and
lambda calculus Lambda calculus (also written as ''λ''-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation ...
. These models rely on programmers or semantics engineers to write mathematical functions in the so-called
continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
. This means that each function consumes a function that represents the rest of the computation relative to this function call. To return a value, the function calls this "continuation function" with a return value; to abort the computation it returns a value. Functional programmers who write their programs in
continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
gain the expressive power to manipulate the flow of control in arbitrary ways. The cost is that they must maintain the invariants of control and continuations by hand, which can be a highly complex undertaking (but see 'continuation-passing style' below).


Uses

Continuations simplify and clarify the implementation of several common
design pattern A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" b ...
s, including
coroutine Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
s/
green thread In computer programming, a green thread is a thread that is scheduled by a runtime library or virtual machine (VM) instead of natively by the underlying operating system (OS). Green threads emulate multithreaded environments without relying on an ...
s and
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
, by providing the basic, low-level primitive which unifies these seemingly unconnected patterns. Continuations can provide elegant solutions to some difficult high-level problems, like programming a web server that supports multiple pages, accessed by the use of the forward and back buttons and by following links. The
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
Seaside web framework uses continuations to great effect, allowing one to program the web server in procedural style, by switching continuations when switching pages. More complex constructs for which ''"continuations provide an elegant description"'' also exist. For example, in C,
longjmp setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions setjmp and longjmp provide this functionality. A t ...
can be used to jump from the middle of one
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
to another, provided the second function lies deeper in the stack (if it is waiting for the first function to return, possibly among others). Other more complex examples include
coroutine Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
s in
Simula 67 Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of ALGOL ...
,
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
, and
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
; tasklets in
Stackless Python Stackless Python, or Stackless, is a Python programming language interpreter, so named because it avoids depending on the C call stack for its own stack. In practice, Stackless Python uses the C stack, but the stack is cleared between function c ...
; generators in
Icon An icon () is a religious work of art, most commonly a painting, in the cultures of the Eastern Orthodox, Oriental Orthodox, and Catholic churches. They are not simply artworks; "an icon is a sacred image used in religious devotion". The most ...
and
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
; continuations in Scala (starting in 2.8);
fibers Fiber or fibre (from la, fibra, links=no) is a natural or artificial substance that is significantly longer than it is wide. Fibers are often used in the manufacture of other materials. The strongest engineering materials often incorporate ...
in
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
(starting in 1.9.1); the
backtracking Backtracking is a class of algorithms for finding solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate ("backtracks") as soon as it de ...
mechanism in
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
; monads in
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
; and threads.


Examples

The
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
programming language includes the control operator
call-with-current-continuation In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
(abbreviated as: call/cc) with which a Scheme program can manipulate the flow of control: (define the-continuation #f) (define (test) (let ((i 0)) ; call/cc calls its first function argument, passing ; a continuation variable representing this point in ; the program as the argument to that function. ; ; In this case, the function argument assigns that ; continuation to the variable the-continuation. ; (call/cc (lambda (k) (set! the-continuation k))) ; ; The next time the-continuation is called, we start here. (set! i (+ i 1)) i)) Using the above, the following code block defines a function test that sets the-continuation to the future execution state of itself: > (test) 1 > (the-continuation) 2 > (the-continuation) 3 > ; stores the current continuation (which will print 4 next) away > (define another-continuation the-continuation) > (test) ; resets the-continuation 1 > (the-continuation) 2 > (another-continuation) ; uses the previously stored continuation 4 For a gentler introduction to this mechanism, see
call-with-current-continuation In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
.


Coroutines

This example shows a possible usage of continuations to implement
coroutines Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
as separate threads. ;;; A naive queue for thread scheduling. ;;; It holds a list of continuations "waiting to run". (define *queue* '()) (define (empty-queue?) (null? *queue*)) (define (enqueue x) (set! *queue* (append *queue* (list x)))) (define (dequeue) (let ((x (car *queue*))) (set! *queue* (cdr *queue*)) x)) ;;; This starts a new thread running (proc). (define (fork proc) (call/cc (lambda (k) (enqueue k) (proc)))) ;;; This yields the processor to another thread, if there is one. (define (yield) (call/cc (lambda (k) (enqueue k) ((dequeue))))) ;;; This terminates the current thread, or the entire program ;;; if there are no other threads left. (define (thread-exit) (if (empty-queue?) (exit) ((dequeue)))) The functions defined above allow for defining and executing threads through
cooperative multitasking Cooperative multitasking, also known as non-preemptive multitasking, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, in order to run multiple ...
, i.e. threads that yield control to the next one in a queue: ;;; The body of some typical Scheme thread that does stuff: (define (do-stuff-n-print str) (lambda () (let loop ((n 0)) (format #t "~A ~A\n" str n) (yield) (loop (+ n 1))))) ;;; Create two threads, and start them running. (fork (do-stuff-n-print "This is AAA")) (fork (do-stuff-n-print "Hello from BBB")) (thread-exit) The previous code will produce this output: This is AAA 0 Hello from BBB 0 This is AAA 1 Hello from BBB 1 This is AAA 2 Hello from BBB 2 ...


Implementation

A program must allocate space in memory for the variables its functions use. Most programming languages use a
call stack In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or ma ...
for storing the variables needed because it allows for fast and simple allocating and automatic deallocation of memory. Other programming languages use a
heap Heap or HEAP may refer to: Computing and mathematics * Heap (data structure), a data structure commonly used to implement a priority queue * Heap (mathematics), a generalization of a group * Heap (programming) (or free store), an area of memory f ...
for this, which allows for flexibility at a higher cost for allocating and deallocating memory. Both of these implementations have benefits and drawbacks in the context of continuations.


Programming language support

Many programming languages exhibit first-class continuations under various names; specifically: *
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...

cl-cont
One can also use custom macros * C# /
VB.NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...
: async and await: "sign up the rest of method as the continuation, and then return to your caller immediately; the task will invoke the continuation when it completes.
Asynchronous Programming for C#
*
Factor Factor, a Latin word meaning "who/which acts", may refer to: Commerce * Factor (agent), a person who acts for, notably a mercantile and colonial agent * Factor (Scotland), a person or firm managing a Scottish estate * Factors of production, suc ...
: callcc0 and callcc1 *
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
: The Continuation
monad Monad may refer to: Philosophy * Monad (philosophy), a term meaning "unit" **Monism, the concept of "one essence" in the metaphysical and theological theory ** Monad (Gnosticism), the most primal aspect of God in Gnosticism * ''Great Monad'', an ...
in Control.Monad.Cont
/code> *
Haxe Haxe is an open source high-level cross-platform programming language and compiler that can produce applications and source code, for many different computing platforms from one code-base. It is free and open-source software, released under the ...

haxe-continuation
*
Icon An icon () is a religious work of art, most commonly a painting, in the cultures of the Eastern Orthodox, Oriental Orthodox, and Catholic churches. They are not simply artworks; "an icon is a sacred image used in religious devotion". The most ...
,
Unicon Unicon, previously known as UNICON, is the World Unicycling Convention and Championships sanctioned by the International Unicycling Federation (IUF). The IUF sanctions a biennial world unicycling convention and competition, the major event on t ...
: create, suspend, @ operator: coexpressions *
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...

Lightwolfjavaflow
(requires bytecode manipulation at runtime or compile time) * Kotlin : Continuation * JavaScript Rhino : Continuation *
Parrot Parrots, also known as psittacines (), are birds of the roughly 398 species in 92 genera comprising the order Psittaciformes (), found mostly in tropical and subtropical regions. The order is subdivided into three superfamilies: the Psittacoid ...
: Continuation PMC; uses
continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
for all control flow *
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...

Coro
an
Continuity
*
Pico Pico may refer to: Places The Moon * Mons Pico, a lunar mountain in the northern part of the Mare Imbrium basin Portugal * Pico, a civil parish in the municipality of Vila Verde * Pico da Pedra, a civil parish in the municipality of Ribeir ...
: call(exp()) and continue(aContinuation, anyValue) *
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
:
PyPy PyPy () is an implementation of the Python programming language. PyPy often runs faster than the standard implementation CPython because PyPy uses a just-in-time compiler. Most Python code runs well on PyPy except for code that depends on CPytho ...
's _continuation.continulet
/code> * Racket:
call-with-current-continuation In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
(commonly shortened to call/cc) *
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
: callcc * Scala: scala.util.continuations provides shift/reset *
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
:
call-with-current-continuation In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
(commonly shortened to call/cc) *
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
: Continuation currentDo:; in most modern Smalltalk environments continuations can be implemented without additional VM support. *
Standard ML of New Jersey Standard ML of New Jersey (SML/NJ; Standard Meta-Language of New Jersey) is a free and open-source compiler and programming environment for the Standard ML programming language. Aside from its runtime system, which is written in C, SML/NJ is wr ...
: SMLofNJ.Cont.callcc *
Unlambda Unlambda is a minimal, "nearly pure" functional programming language invented by David Madore. It is based on combinatory logic, an expression system without the lambda operator or free variables. It relies mainly on two built-in functions (s a ...
: c, the flow control operation for call with current continuation In any language which supports closures and proper tail calls, it is possible to write programs in
continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
and manually implement call/cc. (In continuation-passing style, call/cc becomes a simple function that can be written with
lambda Lambda (}, ''lám(b)da'') is the 11th letter of the Greek alphabet, representing the voiced alveolar lateral approximant . In the system of Greek numerals, lambda has a value of 30. Lambda is derived from the Phoenician Lamed . Lambda gave rise ...
.) This is a particularly common strategy in
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
, where it is easy to construct a "continuation-passing
monad Monad may refer to: Philosophy * Monad (philosophy), a term meaning "unit" **Monism, the concept of "one essence" in the metaphysical and theological theory ** Monad (Gnosticism), the most primal aspect of God in Gnosticism * ''Great Monad'', an ...
" (for example, the Cont monad and ContT monad transformer in the mtl library). The support for proper tail calls is needed because in continuation-passing style no function ever returns; ''all'' calls are tail calls.


In Web development

One area that has seen practical use of continuations is in
Web programming Web development is the work involved in developing a website for the Internet (World Wide Web) or an intranet (a private network). Web development can range from developing a simple single static page of plain text to complex web applications, ...
. The use of continuations shields the programmer from the stateless nature of the
HTTP The Hypertext Transfer Protocol (HTTP) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, ...
protocol. In the traditional model of web programming, the lack of state is reflected in the program's structure, leading to code constructed around a model that lends itself very poorly to expressing computational problems. Thus continuations enable code that has the useful properties associated with
inversion of control In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as compa ...
, while avoiding its problems. Inverting back the inversion of control or, Continuations versus page-centric programming
/cite> is a paper that provides a good introduction to continuations applied to web programming.


Kinds

Support for continuations varies widely. A programming language supports ''re-invocable'' continuations if a continuation may be invoked repeatedly (even after it has already returned). Re-invocable continuations were introduced by
Peter J. Landin Peter John Landin (5 June 1930 – 3 June 2009) was a British computer scientist. He was one of the first to realise that the lambda calculus could be used to model a programming language, an insight that is essential to the development of bo ...
using his J (for Jump) operator that could transfer the flow of control back into the middle of a procedure invocation. Re-invocable continuations have also been called "re-entrant" in the Racket language. However this use of the term "re-entrant" can be easily confused with its use in discussions of multithreading. A more limited kind is the ''escape continuation'' that may be used to escape the current context to a surrounding one. Many languages which do not explicitly support continuations support
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
, which is equivalent to escape continuations and can be used for the same purposes. C's
setjmp/longjmp setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions setjmp and longjmp provide this functionality. A ...
are also equivalent: they can only be used to unwind the stack. Escape continuations can also be used to implement
tail call elimination In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion (computer s ...
. One generalization of continuations are
delimited continuation In programming languages, a delimited continuation, composable continuation or partial continuation, is a "slice" of a continuation frame that has been reified into a function. Unlike regular continuations, delimited continuations return a value, a ...
s. Continuation operators like call/cc capture the ''entire'' remaining computation at a given point in the program and provide no way of delimiting this capture. Delimited continuation operators address this by providing two separate control mechanisms: a ''prompt'' that delimits a continuation operation and a ''reification'' operator such as shift or control. Continuations captured using delimited operators thus only represent a slice of the program context.


Disadvantages

Continuations are the functional expression of the
GOTO GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
statement, and the same caveats apply. While they are a sensible option in some special cases such as web programming, use of continuations can result in code that is difficult to follow. In fact, the
esoteric programming language An esoteric programming language (sometimes shortened to esolang) is a programming language designed to test the boundaries of computer programming language design, as a proof of concept, as software art, as a hacking interface to another language ...
Unlambda Unlambda is a minimal, "nearly pure" functional programming language invented by David Madore. It is based on combinatory logic, an expression system without the lambda operator or free variables. It relies mainly on two built-in functions (s a ...
includes
call-with-current-continuation In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
as one of its features solely because expressions involving it "tend to be hopelessly difficult to track down." The external links below illustrate the concept in more detail.


Linguistics

In "Continuations and the nature of quantification",
Chris Barker Christopher Andrew Barker (2 March 1980 – 1 January 2020) was an English professional footballer who played as a defender. He represented Alfreton Town, Barnsley, Cardiff City, Stoke City, Colchester United, Queens Park Rangers, Plymouth Arg ...
introduced the "continuation hypothesis", that
some linguistic expressions (in particular, QNPs uantificational noun phrases have denotations that manipulate their own continuations.
Barker argued that this hypothesis could be used to explain phenomena such as ''duality of NP meaning'' (e.g., the fact that the QNP "everyone" behaves very differently from the non-quantificational noun phrase "Bob" in contributing towards the meaning of a sentence like "Alice sees ob/everyone), ''scope displacement'' (e.g., that "a raindrop fell on every car" is interpreted typically as \forall c \exists r, \mbox(r,c) rather than as \exists r \forall c, \mbox(r,c)), and ''scope ambiguity'' (that a sentence like "someone saw everyone" may be ambiguous between \exists x \forall y, \mbox(x,y) and \forall y \exists x, \mbox(x,y)). He also observed that this idea is in a way just a natural extension of Richard Montague's approach in "The Proper Treatment of Quantification in Ordinary English" (PTQ), writing that "with the benefit of hindsight, a limited form of continuation-passing is clearly discernible at the core of Montague’s (1973) PTQ treatment of NPs as generalized quantifiers". The extent to which continuations can be used to explain other general phenomena in natural language is a topic of current research.See for example Chris Barker,
Continuations in Natural Language
(Continuations Workshop 2004), or Chung-chieh Shan,
Linguistic Side Effects
(in "Direct compositionality,'' ed. Chris Barker and Pauline Jacobson, pp. 132-163, Oxford University Press, 2007).


See also

*
Call-with-current-continuation In the Scheme computer programming language, the procedure call-with-current-continuation, abbreviated call/cc, is used as a control flow operator. It has been adopted by several other programming languages. Taking a function f as its only argum ...
* Closure *
COMEFROM In computer programming, COMEFROM (or COME FROM) is an obscure control flow structure used in some programming languages, originally as a joke. COMEFROM is the inverse of GOTO in that it can take the execution state from any arbitrary point in code ...
*
Continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
*
Control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
*
Coroutine Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
*
Delimited continuation In programming languages, a delimited continuation, composable continuation or partial continuation, is a "slice" of a continuation frame that has been reified into a function. Unlike regular continuations, delimited continuations return a value, a ...
*
Denotational semantics In computer science, denotational semantics (initially known as mathematical semantics or Scott–Strachey semantics) is an approach of formalizing the meanings of programming languages by constructing mathematical objects (called ''denotations'' ...
*
GOTO GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
*
Spaghetti stack In computer science, an in-tree or parent pointer tree is an -ary tree data structure in which each node has a pointer to its parent node, but no pointers to child nodes. When used to implement a set of stacks, the structure is called a spaghett ...
*
Quaject In computer science, a quaject is an object-like data structure containing both data and code (or pointers to code), exposed as an interface in the form of '' callentries'', and can accept a list of callentries to other quajects for '' callbacks'' a ...
s, a type of object which allows selectable continuations (called 'callouts') to be set for methods on a per-object basis, through Dependency Injection.


References


Further reading

*
Peter Landin Peter John Landin (5 June 1930 – 3 June 2009) was a British computer scientist. He was one of the first to realise that the lambda calculus could be used to model a programming language, an insight that is essential to the development of both ...
. ''A Generalization of Jumps and Labels'' Report. UNIVAC Systems Programming Research. August 1965. Reprinted in Higher Order and Symbolic Computation, 11(2):125-143, 1998, with a foreword by Hayo Thielecke. *
Drew McDermott Drew McDermott (December 27, 1949 – May 26, 2022) was a professor of Computer Science at Yale University. He was known for his contributions in artificial intelligence and planning. Education Drew McDermott earned Bachelor of Science, B.S., Mas ...
and
Gerry Sussman Gerald Jay Sussman (born February 8, 1947) is the Panasonic Professor of Electrical engineering, Electrical Engineering at the Massachusetts Institute of Technology (MIT). He received his Bachelor of Science, S.B. and Doctor of Philosophy, Ph.D. ...
. ''The Conniver Reference Manual'' MIT AI Memo 259. May 1972. *
Daniel Bobrow Daniel Gureasko Bobrow (29 November 1935 – 20 March 2017) was an American computer scientist who created an oft-cited artificial intelligence program STUDENT, with which he earned his PhD., worked at BBN Technologies (BBN), then was a Research Fe ...
: ''A Model for Control Structures for Artificial Intelligence Programming Languages'' IJCAI 1973. *
Carl Hewitt Carl Eddie Hewitt () is an American computer scientist who designed the Planner programming language for automated planningCarl Hewitt''PLANNER: A Language for Proving Theorems in Robots''IJCAI. 1969. and the actor model of concurrent computing, ...
,
Peter Bishop Peter Bishop is a fictional character of the Fox television series ''Fringe''. He is portrayed by Joshua Jackson Joshua Carter Jackson (born June 11, 1978) is a Canadian-American actor. He is known for his starring role as Charlie Conway in ...
and Richard Steiger. ''A Universal Modular Actor Formalism for Artificial Intelligence'' IJCAI 1973. *
Christopher Strachey Christopher S. Strachey (; 16 November 1916 – 18 May 1975) was a British computer scientist. He was one of the founders of denotational semantics, and a pioneer in programming language design and computer time-sharing.F. J. Corbató, et al., ...
and
Christopher P. Wadsworth Christopher is the English version of a Europe-wide name derived from the Greek name Χριστόφορος (''Christophoros'' or '' Christoforos''). The constituent parts are Χριστός (''Christós''), "Christ" or "Anointed", and φέρει ...
. ''Continuations: a Mathematical semantics for handling full jumps'' Technical Monograph PRG-11. Oxford University Computing Laboratory. January 1974. Reprinted in Higher Order and Symbolic Computation, 13(1/2):135—152, 2000, with a foreword by Christopher P. Wadsworth. *
John C. Reynolds John Charles Reynolds (June 1, 1935 – April 28, 2013) was an American computer scientist. Education and affiliations John Reynolds studied at Purdue University and then earned a Doctor of Philosophy (Ph.D.) in theoretical physics from Harvard U ...
. ''Definitional Interpreters for Higher-Order Programming Languages'' Proceedings of 25th ACM National Conference, pp. 717–740, 1972. Reprinted in Higher-Order and Symbolic Computation 11(4):363-397, 1998, with a foreword. *John C. Reynolds. ''On the Relation between Direct and Continuation Semantics'' Proceedings of Second Colloquium on Automata, Languages, and Programming. LNCS Vol. 14, pp. 141–156, 1974. * *
Gerald Sussman Gerald Jay Sussman (born February 8, 1947) is the Panasonic Professor of Electrical Engineering at the Massachusetts Institute of Technology (MIT). He received his S.B. and Ph.D. degrees in mathematics from MIT in 1968 and 1973 respectively. He ...
and
Guy Steele Guy Lewis Steele Jr. (; born October 2, 1954) is an American computer scientist who has played an important role in designing and documenting several computer programming languages and technical standards. Biography Steele was born in Missouri ...
. ''SCHEME: An Interpreter for Extended Lambda Calculus'' AI Memo 349, MIT Artificial Intelligence Laboratory, Cambridge, Massachusetts, December 1975. Reprinted in Higher-Order and Symbolic Computation 11(4):405-439, 1998, with a foreword. *
Robert Hieb The name Robert is an ancient Germanic given name, from Proto-Germanic "fame" and "bright" (''Hrōþiberhtaz''). Compare Old Dutch ''Robrecht'' and Old High German ''Hrodebert'' (a compound of '' Hruod'' ( non, Hróðr) "fame, glory, honou ...
,
R. Kent Dybvig R. Kent Dybvig is a professor emeritus of computer science at Indiana University Bloomington, in Bloomington, Indiana. His research focuses on programming languages, and he is the principal developer of the optimizing Chez Scheme compiler and runt ...
, Carl Bruggeman. ''Representing Control in the Presence of First-Class Continuations'' Proceedings of the ACM SIGPLAN '90 Conference on Programming Language Design and Implementation, pp. 66–77. * Will Clinger, Anne Hartheimer, Eric Ost. ''Implementation Strategies for Continuations'' Proceedings of the 1988 ACM conference on LISP and Functional Programming, pp. 124–131, 1988. Journal version: Higher-Order and Symbolic Computation, 12(1):7-45, 1999. *
Christian Queinnec Christians () are people who follow or adhere to Christianity, a monotheistic Abrahamic religion based on the life and teachings of Jesus Christ. The words ''Christ'' and ''Christian'' derive from the Koine Greek title ''Christós'' (Χρισ ...
. ''Inverting back the inversion of control or, Continuations versus page-centric programming'' SIGPLAN Notices 38(2), pp. 57–64, 2003.


External links

* ACM
SIGPLAN SIGPLAN is the Association for Computing Machinery's Special Interest Group on programming languages. Conferences * Principles of Programming Languages (POPL) * Programming Language Design and Implementation (PLDI) * International Symposium on M ...
br>Workshop on Continuations 2011
at the
ICFP The ACM SIGPLAN International Conference on Functional Programming (ICFP) is an annual academic conference in the field of computer science sponsored by the ACM SIGPLAN, in association with IFIP Working Group 2.8 (Functional Programming). The con ...
.
Continuations for Curmudgeons
by Sam Ruby

by Dorai Sitaram features a nice chapter on continuations.

by Christian Tismer

* ttps://web.archive.org/web/20060501194520/http://www.brics.dk/~cw97/ On-line proceedings of the Second ACM SIGPLAN Workshop on Continuationsbr>Continuation, functions and jumpshttp://okmij.org/ftp/continuations/
by Oleg Kiselyov *https://wiki.haskell.org/Continuations
Rhino With ContinuationsContinuations in pure Java
from the RIFE web application framework
Debugging continuations in pure Java
from the RIFE web application framework

{{Formal semantics Control flow Articles with example Scheme (programming language) code