乐正

Actions speak louder than words.

Sicp-ex2-54

问题

如果两个表包含着同样的元素,这些元素也按同样的顺序排列,那么就称这两个表equal?。 例如:

1
(equal? '(this is a list) '(this is a list))

是真,而

1
(equal? '(this is a list) '(this (is a ) list))

是假。说的更准确些,我们可以从符号相等的基本eq?出发,以递归方式定义出equal?abequal?的,如果它们都是符合,而且这两个符号满足eq?;或者它们都是表, 而(car a)(car b)相互equal?,它们的(cdr a)(cdr b)也是equal?。请利 用这一思路定义出equal?过程。

解答

练习2.54 (ex2-54.scm) download
1
2
3
4
5
(define (equal? x y)
  (if (and (pair? x) (pair? y))
    (and (equal? (car x) (car y))
         (equal? (cdr x) (cdr y)))
    (eq? x y)))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(equal? '(this is a list) '(this is a list))
;Value: #t

(equal? '(this is a list) '(this (is a) list))
;Value: #f

(equal? '() '(a b))
;Value: #f

(equal? '() '())
;Value: #t

(equal? '(this is list)
  '(this (is a) list))
;Value: #f

draft

« sicp-ex2-53 sicp-ex2-55 »

Comments