Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 2.54

From Drewiki
Jump to: navigation, search

Contents

Problem

Two lists are said to be equal? if they contain equal elements arranged in the same order. For example,

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

is true, but

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

is false.

Implement equal? as a procedure.

Discussion

This procedure is easily implemented using recursion. In the dialect of Scheme used in the text, the primitive eq? is only defined when its two arguments are symbols, so in addition to handling the cases where the arguments to equal? are both lists or both symbols, we must also handle the cases when one or both are null?. If we knew that eq? were defined for null? arguments, or for the case where only one argument is a symbol, we could simplify this definition.

Solution

(define (equal? a b)
  (cond ((and (pair? a) (pair? b))
         (and (equal? (car a) (car b))
              (equal? (cdr a) (cdr b))))
        ((or (pair? a) (pair? b))
         #f)
        ((and (null? a) (null? b))
         #t)
        ((or (null? a) (null? b))
         #f)
        (else (eq? a b))))

Tests

(equal? 'a 'a)

Output:

#t


(equal? 'a '())

Output:

#f


(equal? '() '())

Output:

#t


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

Output:

#t


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

Output:

#f


(equal? '(a b c) 'b)

Output:

#f
Personal tools