CPS refresher

Aus ProgrammingWiki

CPS Refresher

To refresh our memory, let's CPS the factorial procedure. Here is the definition of fact in direct style.

Here is fact-cps, which is the CPSed version of fact.

We could use the identity procedure (lambda (v) v) as the initial continuation,

but we want to signal an error if the initial continuation is invoked more than once. Therefore, we will use the continuation returned from calling the following empty-k procedure:

Since fact-cps consumes two arguments instead of one, we might find it convenient to also define a "driver" procedure called fact.

Just for fun, and to demonstrate how empty-k behaves, let's write an incorrect definition of fact-cps that invokes the continuation k multiple times.

When we test our new version, we get an error:

Here is one more example, using the Fibonacci procedure. First we define fib in direct style.

Now we transform fib into continuation-passing style.

Once again, we can define a driver procedure if we like.


Found on http://www.cs.indiana.edu/cgi-pub/lkuper/c311/cps-refresher, slightly modified by CW.
cps-refresher.txt · Last modified: 2009/10/08 09:10 by lkuper