Continuation-passing style (CPS) is a style of programming in which control flow is expressed by passing one or more continuation functions as arguments to other functions, thus making it possible to define computations as a chain of functions, each of which yields control to the next in the chain. It is a major programming technique underlying modern functional languages.
Continuation-passing style (CPS) is a style of programming that expresses control flow by making use of a continuation function. A continuation function is a function that is passed as an argument to other functions, and which is responsible for processing the result returned by the said function. In effect, the caller of a function will pass a callable object (e.g., a function, or a lambda expression), and this object will be invoked when the called function returns. The invocation of the callable object will then constitute the next step in the control flow.
The term “continuation” is used because the flow of a program, rather than being linear, is given as a set of nested calls, which each pass control to each other. This allows for a flexible and powerful model of control flow. CPS is a popular approach in functional programming in general, and is used in many programming languages such as Scheme, Common Lisp, and Haskell.
CPS is often used to create coroutines, which allow a function to save its execution state and suspend its execution, so that it can be resumed later. This allows multiple functions to execute concurrently, offering the possibility of cooperatively multitasking. Similarly, CPS is used for non-preemptive scheduling, a scheduling mechanism that is more lightweight than preemptive scheduling and which allows multiple tasks to run concurrently.
CPS also is often used for a variety of purposes, such as for concurrency control and for implementing dataflow programming languages, which allow for the expression of data-dependent control flow.
Finally, CPS can also be used to simplify some types of code transformation and code optimization. For example, CPS can be used to express tail call elimination, the process of converting recursive functions into non-recursive and thus more efficient equivalents.
Continuation-passing style (CPS) is an important programming approach used in many modern programming languages. It is used to create systems that allow for flexible control flow, such as for implementing coroutines, and it is also used for concurrency control and for code optimization.