Continuation Passing Style
April 3, 2018
Following the Wikipedia article, we give the continuation passing style version of a function to compute the hypotenuse of a right triangle using the Pythagorean theorem; here are normal and continuation passing style versions:
(define (pyth x y) (sqrt (+ (* x x) (* y y))))
(define (pyth& x y k) ((cps *) x x (lambda (x2) ((cps *) y y (lambda (y2) ((cps +) x2 y2 (lambda (x2+y2) ((cps sqrt) x2+y2 k))))))))
> (pyth& 3 4 (lambda (x) x)) 5
You can run the program at https://ideone.com/kPFH79.
Here’s a solution in Python 3 that implements greatest common divisor for non-negative arguments, in continuation passing style.
Output: