my attempt to do the exercises in sicp.

Monday, July 7, 2008

sicp exercise 2.5



;  Exercise 2.5. Show that we can represent pairs of nonnegative integers using only numbers and arithmetic operations if we represent the pair a and b as the integer that is the product 2^a 3^b. Give the corresponding definitions of the procedures cons, car, and cdr.


(define (square x)( * x x))

(define (power base exp)
  (define (func n b res)
    (cond ((= n 0) res)
          ((even? n) (func (/ n 2) (square b) res))
          (else (func (- n 1) b (* res b)))))
  (func exp base 1))


; since i couldnt find any better method, hence the name
(define (count-power-bad base num)
  (define (iter res count)
    (if (not (= (remainder res base) 0))
         count
         (iter (/ res base) (+ count 1))))
  (iter num 0))

(define (cons a b)
  (* (power 2 a) (power 3 b)))

(define (car z)
  (count-power-bad 2 z))

(define (cdr z)
  (count-power-bad 3 z))

(display (car (cons 10 20))) (newline)
(display (cdr (cons 10 20))) (newline)

No comments: