CPS refresher
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.
<eval id="4b41f66090954"> (fact-cps 5 display) </eval>
Since fact-cps consumes two arguments instead of one, we might find it convenient to also define a "driver" procedure called 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:
<eval id="4b41f66091123"> (empty-k) </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>
Error in empty-k: k invoked in non-tail position. Type (debug) to enter the debugger.
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 cps-refresher.txt · Last modified: 2009/10/08 09:10 by lkuper