我的解决方案是sicp练习2.54对吗?

时间:2015-06-25 03:04:50

标签: scheme sicp

我觉得这个练习很有意思。这是我的解决方案:

(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)))

是不是?我想知道(等式?a b)是否为真,(等于?a b)应该始终为真。

1 个答案:

答案 0 :(得分:2)

我认为我们可以通过考虑其他数据类型来提供更准确的答案,并递归地测试适当/不正确列表中的元素。这是我的镜头:

(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))))

对于问题的最后部分,我建议你看看这个非常详细的answer