sicp 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 2a 3b. Give the corresponding definitions of the procedures cons, car, and cdr.

 

 

 

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

(define (count-factors n a)
  (if (not (= (remainder n a) 0))
      0
      (+ 1 (count-factors (/ n a) a))))

(define (car z)
  (count-factors z 2))

(define (cdr z)
  (count-factors z 3))

(define (power x n)
  (if (= n 0)
      1
      (* x (power x (- n 1)))))

(cons 4 9)
(car (cons 4 9))
(cdr (cons 4 9))

 

 

314928

4

9

你可能感兴趣的:(SICP)