SICP 全笔记

Exercise 2.4. Here is an alternative procedural representation of pairs. For this representation, verify that (car (cons x y)) yields x for any objects x and y.

(define (cons x y)
  (lambda (m) (m x y)))

(define (car z)
  (z (lambda (p q) p)))

What is the corresponding definition of cdr? (Hint: To verify that this works, make use of the substitution model of section 1.1.5.)

这个练习使用 lambda 来表示数据。

这个练习是课本中 cons 表示方法的另一种形式

(define (cons x y)
  (define (dispatch m)
    (cond ((= m 0) x)
          ((= m 1) y)
          (else (error "Argument not 0 or 1 -- CONS" m))))
  dispatch)

(define (car z) (z 0))

(define (cdr z) (z 1))

现在可以再写为:

(define (new-cons x y)
  (lambda (m) (m x y)))

(define (new-car z)
  (z (lambda (x y) x)))

;; the corresponding definition of cdr:
(define (new-cdr z)
  (z (lambda (x y) y)))

;;; tests begin
(load "../testframe.scm")

(asserteq? (new-car (new-cons 'a 'b)) 'a)
(asserteq? (new-cdr (new-cons 'a 'b)) 'b)

注意,这并不是说,现在使用的 scheme 系统中的 cons car cdr 可以用这样的形式来替代。这也是我们为什么将其名字前缀了 new

因为我们只是更改了部分与数据的表现形式相关的操作而已,比如 pair?procedure? 这些谓词我们依然没有更改。倘若我们将这个程序的 load 写在 cons 的定义之后,load 将会出现错误

1 ]=>
;Loading "../testframe.scm"...
;The object (assert-equal eq? e1 e2) is not applicable.

这里的练习仅仅只是表示一种可能性而已。