CSE 413 Winter 2001

Assignment 1 Sample Solution

Part I.

  1.   


  2.  
    1. pig
    2. cow
    3. ((dog cow pig) pig cow dog)
    4. cow
    5. ((cow pig) pig cow dog)
    6. #f
    7. #t
    8. #t
    9. #t
    10. #f
    11. ((car a) pig cow dog)
    12. #t

Part II.

  1. ;;; = greatest common divisor of x, y
    (define (gcd x y)
      (cond ((= x 0) y)
            ((= y 0) x)
            ((= x y) x)
            ((> x y) (gcd (- x y) y))
            ((< x y) (gcd x (- y x)))))
  2. ;;; = 2nd to last element of alist, or null if alist has < 2 elements
    (define (2nd-last alist)
      (if (< (length alist) 2)
          ()
          (cadr (reverse alist))))
  3. ;;; = sum of digits in decimal representation of n
    (define (decimal-digit-sum n)
      (if (= n 0)
          0
          (+ (modulo n 10)
             (decimal-digit-sum (quotient n 10)))))
    
    ;;; = sum of the digits of integers in alist
    ;;; (this handles negative numbers, but that was not required)
    (define (sum-digits alist)
      (if (null? alist)
           0
           (+ (if (number? (car alist)) 
                  (decimal-digit-sum (abs (car alist)))
                  0)
              (sum-digits (cdr alist)))))
  4. ;;; = depth of alist
    (define (depth alist)
      (if (pair? alist)
          (max (+ 1 (depth (car alist)))
               (depth (cdr alist)))
          0))
  5. ;;; = nth fibonocci number (efficiently)
    (define (fib n)
      (tail-fib n 0 1))
    
    ;;; given the current and next number in the fibonocci sequence,
    ;;; return the fibonocci number that is k numbers further in the sequence.
    ;;; (k=0 means return the current number, k=1 means the next one, etc.)
    (define (tail-fib k current next)
      (if (= k 0)
          current
          (tail-fib (- k 1) next (+ current next))))