乐正

Actions speak louder than words.

Sicp-ex2-5

问题

请证明,如果将$a$和$b$表示为乘积$2^a3^b$对应的整数,那么我们就可以只用非负整数 和算数运算表示序对。请给出对应的过程conscarcdr的定义。

解答

练习2.5 (ex2-5.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(define (cons a b)
  (* (expt 2 a)
     (expt 3 b)))

(define (car z)
  (define (f n c)
    (if (not (= (remainder n 2) 0))
        c
        (f (/ n 2) (+ c 1))))

  (f z 0))

(define (cdr z)
  (define (f n c)
    (if (not (= (remainder n 3) 0))
        c
        (f (/ n 3) (+ c 1))))

  (f z 0))

测试

1
2
3
4
5
6
7
8
(define z (cons 3 4))
;Value: z

(car z)
;Value: 3

(cdr z)
;Value: 4

draft

« sicp-ex2-4 sicp-ex2-6 »

Comments