我对 sicp 练习 2.54 的解决方案正确吗?
Is my solution to sicp exercise 2.54 right?
我觉得这个练习很有趣。这是我的解决方案:
(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)))
对吗?我想知道 (eq?a b) 是否为真,(equal?a b) 应该总是为真。
我认为我们可以通过考虑其他数据类型并递归测试proper/improper列表中的元素来给出更准确的答案。这是我的镜头:
(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。
我觉得这个练习很有趣。这是我的解决方案:
(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)))
对吗?我想知道 (eq?a b) 是否为真,(equal?a b) 应该总是为真。
我认为我们可以通过考虑其他数据类型并递归测试proper/improper列表中的元素来给出更准确的答案。这是我的镜头:
(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。