Dan's Thoughts Thinking somewhat carefully

21Jul/090

Exercise 2.5 of SICP

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

The discrete log procedure is a cousin of discrete-log from 1.45.

(define (cons a b)
  (* (expt 2 a) (expt 3 b)))
 
(define (car x)
  (discrete-log x 2))
 
(define (cdr x)
  (discrete-log x 3))
 
(define (discrete-log n base)
  (if (not
        (= 0 (remainder n base)))
    0
    (+ 1 (discrete-log (/ n base) base))))
Filed under: lisp, SICP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

Spam protection by WP Captcha-Free

No trackbacks yet.