S5. Quiz2 Solutions

posted Oct 29, 2012, 8:39 AM by Samuel Konstantinovich   [ updated Nov 15, 2012, 5:13 AM ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;FIRST VERSION
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define U '( (3 15) 2 (1 (0 4) 32 ) 7 ))      
;1. How many top level elements are in list U?
;4

;2. What is (car U)?
;(car U) is (3 15)

;3. What is (caddr U)?
;(caddr U) is (1 (0 4) 32)

;4. Write an expression to get 15 from list U.
;(cadar U) gives 15.

;5. Write an expression that would get 0 from list U.
;(caadar(cddr U)) gives 0

(define (g x y)
  (cond 
    ((null? y) x)
    (else 
       (cons (car y) (g x (cdr y))))))
;6. Using the function g defined above trace and evaluate:
;(g '( 1 3 6) '(4 5 8) )
;(cons 4( g (1 3 6)(5 8)) 
;            (cons 5( g (1 3 6)(8)) 
;                       (cons 8( g (1 3 6)()) 
;                                   (1 3 6)
;
;The end result is (4 5 8 1 3 6)

;7. Write a function (change P x)that takes a list of integers P and an integer x,
;and doubles any of the list’s values that are divisible by x
(define (change P x)
  (cond
    ((null? P) P)
    ((list? (car P)) (cons (change (car P) x)(change (cdr P) x)))
    ((= 0(remainder (car P) x)) (cons (* 2 (car P)) (change (cdr P) x)))
    (else (cons (car P)(change (cdr P) x)))))
;(change '( 4 15 11 3 0) 3)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;SECOND VERSION
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define P '( (13 9 1) (5 (7 2) 4 ) 40 ) )  ;[Use this list for 1-5]
;1. How many top level elements are in list P?
;3 top level elements

;2. What is (car P)?
;(car P) is (13 9 1) 

;3. What is (cadadr P)?
;(cadadr P) is (7 2)

;4. Write an expression that would get 1 from list.P.
;(caddar P) gives 1.

;5. Write an expression that would get 2 from list P.
;(cadr(cadadr P)) gives 2

(define (f a b)
  (cond 
    ((null? a) b)
    (else (cons (car a) (f (cdr a) b)))))

;6. Using the function f defined above evaluate:
;(f '( 3 9 1) '(5 8 7) )
;(cons 3 (f (9 1)(5 8 7))
;            (cons 9 (f (1)(5 8 7))
;                     (cons 1 (f ()(5 8 7))
;                                  (5 8 7)
;
;end result is (3 9 1 5 8 7)


;7. Write a function (change P x) that takes a list of integers P
;and an integer x, and negates any of the list’s values that are
;multiples of x
(define (change P x)
  (cond
    ((null? P) P)
    ((list? (car P)) (cons (change (car P) x)(change (cdr P) x)))
    ((= 0(remainder (car P) x)) (cons (- (car P)) (change (cdr P) x)))
    (else (cons (car P)(change (cdr P) x)))))
;(change '( 4 15 11 3 0) 3)

Comments