我的尝试是,
(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)
。任何的想法?
谢谢,
答案 0 :(得分:2)
我会通过循环使用第二个列表来构建看到的元素。如果这是家庭作业,我会觉得很难给你这个 - 更重要的是理解递归是如何工作的,而不仅仅是得到正确的答案。
(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))))))
更新以容纳您的评论 - 这可能不是最干净的解决方案,但应该让您了解它的工作原理。
(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)))))))
答案 1 :(得分:2)
R5RS + SRFI1
(define (remove-duplicates lst)
(fold-right (lambda (f r)
(cons f (filter (lambda (x) (not (equal? x f))) r))) '() lst))
答案 2 :(得分:0)
使用SRFI 1,您可以直接使用delete-duplicates
或delete-duplicates!
:http://srfi.schemers.org/srfi-1/srfi-1.html#delete-duplicates