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.

Advertisements

Pages: 1 2

One Response to “Continuation Passing Style”

  1. Daniel said

    Here’s a solution in Python 3 that implements greatest common divisor for non-negative arguments, in continuation passing style.

    import operator
    
    def cps(fn):
      return lambda *args, **kwargs: args[-1](fn(*args[:-1], **kwargs))
    
    cp_eq = cps(operator.eq)
    cp_mod = cps(operator.mod)
    
    def cp_gcd(a, b, fn):
      return cp_eq(b, 0, lambda x: fn(a) if x else cp_mod(a, b, lambda y: cp_gcd(b, y, fn)))
    
    if __name__ == "__main__":
      cp_print = cps(print)
      cp_gcd(100, 15, lambda x: cp_print(x, lambda _: None))
    

    Output:

    5
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: