CS275

Lab 10

Continuations


This is due on Friday, December 9

 

Exercise 1. Rewrite the the following length procedure as length-acc, which should be tail-recursive and use an accumulating parameter:

(define length
      (lambda (L)
           (cond
                 [(null? l) 0]
                 [else (add1 (length (cdr L)))])))

Exercise 2. Rewrite the the following make-palindrome procedure as make-palindrom-acc, which should be tail-recursive and use an accumulating parameter:

(define make-palindrome
    (lambda (l)
      (cond
 			[(or (null? l) (null? (cdr l))) l]
          [else (cons (car l) (append (make-palindrome (cdr l)) (list (car l))))])))  
		

Exercise 3. Rewrite the the following flatten procedure as flatten-acc, which should be tail-recursive and use an accumulating parameter:

(define flatten
    (lambda (l)      
		(if (null? l) ()
        (if (atom? l) (list l)
			            (append (flatten (car l)) (flatten (cdr l)))))))  

      

Exercises 4, 5, and 6: write length, make-palindrome and flatten in continuation-passing style, calling the new functions length-k, make-palindrome-k and flatten-k.

 

Exercise 7: Here is a deep-recursive procedure pairall. Given two lists this returns a list of all possible pairs where the first element comes from the first list and the second element comes from the second: The call (pairall '(1 2 3) '(a b c)) produces

((1 a) (1 b) (1 c) (2 a) (2 b) (2 c) (3 a) (3 b) (3 c)) 
(define pairone
(lambda (a l) (if (null? l) () (cons (list a (car l)) (pairone a (cdr l)))))) (define pairall (lambda (l1 l2) (if (null? l1) () (append (pairone (car l1) l2) (pairall (cdr l1) l2)))))

Write a CPS version of pairall, pairall-k.

 

Exercise 8: Use call/cc to write a procedure (sum vec) that adds together the numbers in vector vec. So (sum '(1 2 3) ) returns 6. So far this is simple. The catch is that if vec contains anything other than a number, sum prints 'Error. So (sum '(1 2 3 a 4 5)) is 'Error.