Blame


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