Read a Scheme reference and Chapter 8 in the EOPL book.
Write Scheme definitions for the following functions and convert them to CPS. The continuation argument should be the last argument. For example, if you were asked to write factorial and its CPS counterpart, the answer would be:
(define fact (lambda (n) (if (zero? n) 1 (* n (fact (- n 1)))))) (define factcps (lambda (n k) (if (zero? n) (k 1) (factcps (- n 1) (lambda (v) (k (* n v)))))))
(dupla 3 0) ==> '() (dupla 3 1) ==> '(3) (dupla 3 2) ==> '(3 3) (dupla 3 5) ==> '(3 3 3 3 3)
(index 3 '(a b c d e f)) ==> 'd
(remove 1 '(a b c d e f)) ==> '(a c d e f)
(insert 'a 2 '(1 2 3 4 5 6)) ==> '(1 2 a 3 4 5 6)
(fib 0) ==> 0 (fib 1) ==> 1 (fib 2) ==> 1 (fib 8) ==> 21
(filter even? '(1 2 3 4 5 6)) ==> '(2 4 6) (filter (lambda (x) (> x 8)) '(1 9 2 10 3 11 4 12)) ==> '(9 10 11 12) (filter (lambda (x) (and (> x 8) (< x 10))) '(1 9 2 10 3 11 4 12)) ==> '(9)When converting to CPS, assume the predicate function has also been converted to CPS.
(map add1 '(1 2 3)) ==> '(2 3 4) (map (lambda (x) (* x 3)) '(1 2 3)) ==> '(3 6 9)When converting to CPS, assume the function has also been converted to CPS.
(powerset '()) ==> '(()) (powerset '(1 2 3)) ==> '((), (3), (2), (2,3), (1), (1,3), (1,2), (1,2,3))
(merge '() '(1 2 3)) ==> '(1 2 3) (merge '(1 2 3) '()) ==> '(1 2 3) (merge '(1 3 5 7 8 9 10) '(2 4 6)) ==> '(1 2 3 4 5 6 7 8 9 10)
(split '()) ==> '(() ()) (split '(1)) ==> '((1) ()) (split '(1 2 3 4 5 6 7 8 9)) ==> '((1 3 5 7 9) (2 4 6 8)) (split '(1 2 3 4 5 6 7 8 9 10)) ==> '((1 3 5 7 9) (2 4 6 8 10))
(mergesort '()) ==> '() (mergesort '(8 1 3 9 6 5 7 2 4 10)) ==> '(1 2 3 4 5 6 7 8 9 10)
sabry@cs.uoregon.edu