Is my solution to sicp exercise 2.54 right?

246 views Asked by At

I find this exercise is interesting. Here's my solution:

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

Is it right ? I wonder if (eq? a b) is true, (equal? a b) should be always true.

1

There are 1 answers

4
Óscar López On BEST ANSWER

I think we can give a more accurate answer by considering other data types, and recursively testing the elements in proper/improper lists. Here's my shot:

(define (same-type? a b)
  (or (and (number? a) (number? b))
      (and (symbol? a) (symbol? b))
      (and (string? a) (string? b))
      (and (list? a) (list? b))
      (and (pair? a) (pair? b))))

(define (my-equal? a b)
  (cond ((not (same-type? a b)) #f)
        ((or (symbol? a) (null? a) (null? b))
         (eq? a b))
        ((list? a)
         (if (not (= (length a) (length b)))
             #f
             (and (my-equal? (car a) (car b))
                  (my-equal? (cdr a) (cdr b)))))
        ((pair? a)
         (and (my-equal? (car a) (car b))
              (my-equal? (cdr a) (cdr b))))
        ((string? a) (string=? a b))
        ((number? a) (= a b))))

For the last part of your question, I suggest you take a look at this very detailed answer.