我必须制作Dr. Racket程序,如果它们跟随自己的相同字母,则从列表中删除字母。例如:(z z f a b b d d)将成为 (z f a b d)。我已经为此编写了代码,但它只是从列表中删除了第一个字母。 有人可以帮忙吗?
#lang racket
(define (remove-duplicates x)
(cond ((null? x)
'())
((member (car x) (cons(car(cdr x)) '())))
(remove-duplicates (cdr x))
(else
(cons (car x) (remove-duplicates (cdr x))))))
(define x '( b c c d d a a))
(remove-duplicates x)
答案 0 :(得分:2)
(define (remove-dups x)
(cond
[(empty? x) '()]
[(empty? (cdr x)) (list (car x))]
[(eq? (car x) (cadr x)) (remove-dups (cdr x))]
[else (cons (car x) (remove-dups (cdr x)))]))
如果您不知道, (cadr x)
是(car (cdr x))
的缩写。
此外,模式匹配使列表解构通常更具可读性。在这种情况下,没有那么多,但它仍然比其他版本更好:
(define (rmv-dups x)
(match x
[(list) (list)]
[(list a) (list a)]
[(cons a (cons a b)) (rmv-dups (cdr x))]
[__ (cons (car x) (rmv-dups (cdr x)))]))
答案 1 :(得分:1)
如果引入辅助函数,这个问题会更简单。
我推荐这样的东西(尖括号意味着你需要填写细节):
(define (remove-duplicates x)
(cond
[ <x is empty> '()] ; no duplicates in empty list
[ <x has one element> x] ; no duplicates in a list with one element
[ <first and second element in x is equal> (cons (car x) (remove-from-front (car x) (cdr x)))]
[else (cons (car x) (remove-duplicates (cdr x)))]))
(define (remove-from-front e x)
(cond
[ <x is empty> '()] ; e is not the first element of x
[ <e equals first element of x> (remove-from-front e (cdr x))] ; skip duplicate
[else (remove-duplicates x)])) ; no more es to remove