CPS refresher

Aus ProgrammingWiki
Archivierte Version vom 2010-01-04T14:17:46+00:00. Aktuelle Version

CPS Refresher

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

<eval id="4b41f6609018c"> (fact 5) </eval>

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

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

<eval id="4b41f66090954"> (fact-cps 5 (lambda (v) v)) </eval>

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:

<eval id="4b41f66091123"> (empty-k) </eval>

<eval id="4b41f66090954"> (fact-cps 5 (empty-k)) </eval>

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

<eval id="4b41f7e7c5d78"> (fact 5) </eval>

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:

<eval id="4b41f660918f7"> (fact-cps 5 (empty-k)) </eval>

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