#lang racket ; all functions can be written in continuation passing style in which ; the next thing to be done is passed into the call along with the ; arguments. The next thing to be done, cc, is called a continuation. ; Programming in this way is called continuation passing style (CPS). (define C+ (lambda (x y cc) (cc (+ x y)))) (define C* (lambda (x y cc) (cc (* x y)))) (C+ 3 5 (lambda (r) r)) ; return result 3 + 5 ; same as ((lambda (r) r) (+ 3 5)) ; to chain a sequence of cps functions computing (3 + 5) * 10 (C+ 3 5 (lambda (r) (C* r 10 (lambda (rr) rr)))) ; this is the same as ; and even for this: (3 + 5) * (8 + 2) i.e. (* (+ 3 5) (+ 8 2) ) ; Note how it reads left to right. (C+ 3 5 (lambda (r1) ( C+ 8 2 (lambda (r2) (C* r1 r2 (lambda (r3) r3) ) ) ) ) ) ; this means that we can even write recursive functions that make ; multiple recursive calls in continuation passing style. The ; stack is replaced by bindings in lambdas to heap values