[plt-scheme] CPS conversion example, question
Grant Rettke writes:
> Today I was reading the Wikipedia article:
> on continuation passing style. It has some example written in Scheme,
> though I'm not sure if they are meant to run or not. In the example of
> converting the "pyth" function from direct style to cps style, for
> example, the direct style runs, but the cps style seems to be written
> backwards.
>
> Nonetheless I wanted to try converting a running example from direct
> style to cps style,...
> ;; Direct style
> (define (pyth-ds x y)
> (sqrt (+ (* x x) (* y y))))
>
;; Let style
(define (pyth-ls x y k)
(let ([x2 (* x x)])
(let ([y2 (* y y)])
(let ([x2py2 (+ x2 y2)])
(let ([result (sqrt x2py2)])
(k result))))))
; CPS Style
(define (pyth-cps x y k)
((λ (x2)
((λ (y2)
((λ (x2py2)
((λ (result)
(k result)) (sqrt x2py2))) (+ x2 y2))) (* y y))) (* x x)))
> Is that the right way to do it?
Don't think so.
The conversion (let ((a b)) (c a)) into ((lambda (a) (c a)) b) has
nothing to do - unless I am wrong - with CPS. Every *inside* operation
should be 'continued'. Think of
let x2 = * x x
y2 = * y y
x2p2 = + x2 y2
in terms of
* x x \x2 ->
* y y \y2 ->
+ x2 y2 \x2p2 -> ...
(using a bastard Schaskell syntax...; this is finally the form presented
on the page you cite.)
Jerzy Karczmarczuk