Here's a different, hopefully less-tricky, implementation. (It's O(n), but it requires both of the incoming lists to be sorted; in comparison, óscar's implementation does not required sorted lists, but it's O(n2).)
(define (diff lhs rhs)
(let loop ((result '())
(lhs lhs)
(rhs rhs))
(cond ((null? lhs) (append-reverse result rhs))
((null? rhs) (append-reverse result lhs))
(else (let ((a (car lhs))
(b (car rhs)))
(cond ((< a b) (loop (cons a result) (cdr lhs) rhs))
((< b a) (loop (cons b result) lhs (cdr rhs)))
(else (loop result (cdr lhs) (cdr rhs)))))))))
Example:
> (diff '(3 6 7) '(1 4 6 7))
(1 3 4)
append-reverse
is from SRFI 1, so in Racket you have to (require srfi/1)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…