What is continuation-passing style?
If a language supports continuations, the programmer can add control constructs like exceptions, backtracking, threads and generators.
Sadly, many explanations of continuations feel vague and unsatisfying. Such power deserves a solid pedagogical foundation.
Continuation-passing style is that foundation.
Continuation-passing style gives continuations meaning in terms of code.
Even better, a programmer can discover continuation-passing style by themselves if subjected to one constraint:
No procedure is allowed to return to its caller — ever.
One hint makes programming in this style possible:
Procedures can take a callback to invoke upon their return value.
When a procedure is ready to “return” to its caller, it invokes the “current continuation” callback (provided by its caller) on the return value.
A continuation is a first-class return point.
- Implementing :
Continuation passing style can be used to implement continuations and control flow operators in a functional language that does not feature first-class continuations but does have first-class functions and tail-call optimization.