Blob


1 ;; 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.
3 (define (expt base n)
4 (if (= n 0)
5 1
6 (* base (expt base (- n 1)))))
8 (define (cons a b)
9 (* (expt 2 a)
10 (expt 3 b)))
12 (define (car x)
13 (if (not (= (remainder x 2) 0))
14 0
15 (1+ (car (/ x 2)))))
16 (define (cdr x)
17 (if (not (= (remainder x 3) 0))
18 0
19 (1+ (cdr (/ x 3)))))
21 (define (test-case actual expected)
22 (load-option 'format)
23 (newline)
24 (format #t "Actual: ~A Expected: ~A" actual expected))
26 (test-case (car (cons 5 9)) 5)
27 (test-case (cdr (cons 5 9)) 9)
28 (test-case (car (cons 12 25)) 12)
29 (test-case (cdr (cons 12 25)) 25)
30 (test-case (car (cons 0 1)) 0)
31 (test-case (cdr (cons 1 0)) 0)
32 (test-case (car (cons 0 6)) 0)
33 (test-case (cdr (cons 9 0)) 0)