Exam II, CS 257

Name:_______________________

CIRT user-id:________________



I want American computers in space. Don't want Russian computers. Russian computers are like Russian booster rockets ... biggest in world.
- Georgy Grechko, former Soviet cosmonaut









  1. What value is printed when you type each of the following to Scheme? (2 points each)
    expressionresult
    (define (foo x)
      (if (= x 0) + *))
    
    ((foo 2) 3 4)
    
     
    (and 'a 'b 'c)
    
     
    (or 'a 'b 'c)
    
     
    (if 'a 'b 'c)
    
     
    (define a '(1 2 3))
    
    `(a ,a b ,@a c (,a) (d ,@a a))
    
     
    
    
    
    
    
    
    
    
    
    
    

  2. Write a tail-recursive definition of add-nums, a function that takes a single argument, a list, a returns the sum of all the elements in the list that were numbers. The sum should not include numbers nested within sublists. Hint: use a helper function of two arguments (6 points for being tail recursive, 4 for being correct)

    Examples:

    (add-nums '())                    ; 0
    (add-nums '(a 1 b 2 c 3 d e))     ; 6
    (add-nums '((1) 2 (a 45 b) c 3))  ; 5
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

  3. Rewrite the following pseudocode in Scheme, using procedure calls in place of goto and assignment. (10 points)
    foo(i,j)
    {
     L1:
      if (i < j) {
        j = j-i;
        goto L1;
      } else if (j < i) {
        i = i-j;
        goto L1;
      } else
        return i;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    

  4. Convert each expression into an equivalent backquote form. (2 points each)
    expressionequivalent using backquote
    (list 'this 'is 'example n 'of m)
    
    `(this is example ,n of ,m)
    (append s1 '(followed by) s2)
    
     
    (cons 'foo (append s '(more)))
    
     
    (list 'joe (list 'the x) 'saw (car y))
    
     
    (cons 'a (car y))
    
     
    (append (list (+ a 3) (+ a 4)) '(and more))
    
     
    
    
    
    
    

  5. Extra credit: Given these definitions
    (define (c-car x c) (c (car x)))
    
    (define (c-cdr x c) (c (cdr x)))
    
    (define (c-cons x lis c) (c (cons x lis)))
    
    (define (c-null? x c1 c2) (if (null? x) (c1) (c2)))
    
    (define (foo a b c)
      (c-null? a
    	   (lambda () (c b))
    	   (lambda ()
    	     (c-car a
    		    (lambda (caa)
    		      (c-cdr a
    			     (lambda (cda)
    			       (foo cda b
    				    (lambda (fcdab)
    				      (c-cons caa fcdab c))))))))))
    
    What does (foo '(x y z) '(p d q) (lambda (x) x)) return? (3 points + Scheme self actualization)