如何删除列表方案中的所有重复元素?

问题描述:

我的尝试是,

(define (remove-dup lst)
  (cond ((null? lst) '())
        ((null? (cdr lst)) (car lst))
        ((equal? (car lst) (car (cdr lst))) (remove-dup (cdr lst)))
        (else (cons (car lst) (remove-dup (cdr lst))))
        )

  )

我的列表是 (a b c a a c c c )我想要的是(a b c).任何想法?

My list was (a b c a a c c c ) What I want is (a b c). Any idea?

谢谢,

我会通过循环使用您构建的可见元素的第二个列表来解决这个问题.如果这是家庭作业,我会为你提供这个感到难过 - 了解递归的工作原理比仅仅拥有正确的答案更重要.

I'd approach this by looping with a second list that you build up of seen elements. I'll feel bad for giving this to you if this was homework though - it's more important to understand how recursion works than to just have the right answer.

(define (remove-dup ls)
  (let loop ((ls ls) (seen '()))
     (cond
       ((null? ls) '())
       ((memq (car ls) seen) (loop (cdr ls) seen))
       (else (cons (car ls) (loop (cdr ls) (cons (car ls) seen))))))

更新以适应您的意见 - 这可能不是最干净的解决方案,但应该让您了解它的工作原理.

Updated to accommodate your comments - this probably isn't the cleanest solution but should give you an idea of how it might work.

(define (rdup ls)
  (let loop ((ls ls) (current #f)) ; this is bad coding style, a "magic" variable you don't expect to see in your list
     (cond
       ((null? ls) '())
       ((null? (cdr ls)) (if (eq? (car ls) current) '() ls))
       ((eq? (car ls) (cadr ls)) (loop (cdr ls) (car ls)))
       ((eq? (car ls) current) (loop (cdr ls) current))
       (else (cons (car ls) (loop (cdr ls) (car ls)))))))