continuation-passing-style


Continuation Passing Style (often abbreviated CPS) is an alternative way of writing programs in which every function called receives a continuation as an additional argument, and in which every function call is in tail position. This makes all continuations explicit. It also makes calling a function and returning a value use the same mechanism, and makes the control usually manifest in the nested structure of expressions into lambda expressions. These unifications can simplify program analysis, and for this reason some Scheme compilers transform code into CPS.

For example, the factorial function

 (define fact 
   (lambda (n) 
     (if (zero? n) 
         1 
         (* n (fact (- n 1)))))) 

would be expressed in CPS as

 (define (fact-cps n C) 
   (if (zero? n) 
       (C 1) 
       (fact-cps (- n 1) 
                 (lambda (result_n-1) 
                   (C (* n result_n-1)))))) 

where we assume that each function takes its continuation as a new first argument. Note that (1) all function calls are in tail position, (2) the order of function calls has been made explicit, (3) all formerly anonymous temporary values (eg n-minus-one, or the factorial-of-n-minus-one) have been given names.

This transformation was first exploited in the Rabbit Scheme compiler, written by WikiPedia:Guy_Steele. In the mid-to-late 1990s an alternative to CPS called A-normal-form? (or ANF) became popular in Scheme compilers, supplanting CPS in some compilers.


category-learning-scheme