Different Notions of Continuation
- Continuation of a program point: It is the sequence of steps left to be performed once execution reaches that program point.
- Continuation of a subexpression: In functional programming languages, all programs are expressions and so a program point is the end of evaluation of a subexpression. The continuation of a subexpression takes the value of the subexpression and feeds it into the rest of the program. Continuation of subexpression of a program is a function that maps value of value of .
The CPS transformation
Functions that are written in continuation passing style (CPS) take a function (continuation) as one of the arguments and end with calling the continuation with a value. The result of the continuation then becomes the result of the function. We can get a value from such a function by passing it the identity function as continuation i.e.
The CPS transformation takes an expression and converts it to a function in continuation-passsing-style where:
- is the continuation
- The body computes the result of and then calls with the result
We’ll see the CPS transformation for call by value programming languages. Here, expressions are evaluated to a value before passing them to a function as arguments. is the CPS transformation and it is defined on a case-by-case basis
The transformation of a constant and a variable is just applying the continuation to the value. The transformation of a function is more interesting. To start with it takes a continuation and supplies it with a function. The supplied function then takes a variable and returns an expression, but in the continuation passing style. This is done because a program written in continuation passing style will expect expressions in the same style.
What happens if we don’t transform the body of function to CPS style? Suppose we had a function which we transform to CPS style as . When a caller calls it with a continuation it expects a function to which it can pass a continuation, but here it gets instead. If we transformed the expression also, we’d have gotten and the caller can pass a continuation to this! This is the transformation of function application. It looks complicated but read it like this: Firstly the result is a function that takes in a continuation. In the body, you first transform to CPS style and pass it a continuation. This continuation will be passed the value of which is . Similarly we evaluate by transforming it to CPS style and passing it a lambda. Finally we do the function application and pass the result to the top-level continuation .
Similar to function application, we first transform to CPS style and pass in a continuation that has a conditional on and supplies to the appropriate branch.