为了达到这个目的,我们必须同时遍历两个列表,特别注意边缘情况。如果我们设法在没有其中一个结束的情况下遍历列表,那么我们可以说它们在结构上是平等的。试试这个:
(define (structurally? exp1 exp2)
; if we reach the end of both lists, they're equal
(cond ((and (null? exp1) (null? exp2)) #t)
; if we reach the end of one before the other, they're distinct
((and (null? exp1) (not (null? exp2))) #f)
; if we reach the end of one before the other, they're distinct
((and (not (null? exp1)) (null? exp2)) #f)
; if we find an atom they're equal, no matter its value
((not (pair? exp1)) #t)
; recursive step: advance over `car` and `cdr` of both lists
; simultaneously, combining all partial results using `and`
(else
(and (structurally? (car exp1) (car exp2))
(structurally? (cdr exp1) (cdr exp2))))))
它按预期工作:
(structurally? '(1 2 (3 a 5) (b 6 c "string" 7 (5)) 9)
'(2 1 (3 "string" 5) (b 6 c a 7 (5)) 9))
=> #t
(structurally? '(1 2 (3 a b 5) (b 6 c "string" 7 (5)) 9)
'(2 1 (3 "string" 5) (b 6 c d a 7 (5)) 9))
=> #f
谢谢!我一直在看这个小时 – user2994363
这种支票的用途是什么? – X10D