爲了達到這個目的,我們必須同時遍歷兩個列表,特別注意邊緣情況。如果我們設法在沒有其中一個結束的情況下遍歷列表,那麼我們可以說它們在結構上是平等的。試試這個:
(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