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.5
我们可以通过如下表示来求出
;;; cons integers
(define (new-cons x y)
(* (expt 2 x) (expt 3 y)))
;; nth root of num = result => get n
(define (nth-root num result)
(if (not (zero? (remainder num result)))
0
(1+ (nth-root (/ num result) result))))
(define (new-car z)
(nth-root z 2))
(define (new-cdr z)
(nth-root z 3))
通过下面的测试来确保结果是正确的:
(load "../testframe.scm")
;; test nth-root
(assert= (nth-root 1024 2) 10) ; 2^10 = 1024
(assert= (nth-root 27 3) 3) ; 3^3 = 27
(assert= (nth-root 625 5) 4) ; 5^4 = 625
(assert= (new-car (new-cons 10 101)) 10)
(assert= (new-cdr (new-cons 10 101)) 101)