问题描述
我在 DrRacket 中使用 Intermediate Student with Lambda,我想知道如何在保持顺序的同时删除列表中的重复项.例如 (remove-dup (list 2 5 4 5 1 2))
会产生 (list 2 5 4 1)
.到目前为止,我有这个:
I am using Intermediate Student with Lambda in DrRacket, I was wondering how one would remove the duplicates in a list, while keeping the order. For example (remove-dup (list 2 5 4 5 1 2))
would produce (list 2 5 4 1)
. So far, I have this:
(define (remove-duplicates lst)
(cond
[(empty? lst) empty]
[(member? (first lst) (rest lst))
(remove-duplicates (rest lst))]
[else (cons (first lst) (remove-duplicates (rest lst)))]))
,但有一个问题,因为它不保持顺序.有人可以指出我正确的方向吗?谢谢你的时间.
, but there's a problem since it doesn't keep the order. Can someone point me in the right direction? Thanks for your time.
推荐答案
如果您的目标是让功能正常工作,而不是一些家庭作业问题,那么您不需要做任何事情,只需使用 remove-duplicates
:
If your goal is to get the functionality working, and not some homework question, then you don't need to do anything, just use remove-duplicates
:
Welcome to Racket v5.2.
-> (remove-duplicates (list 2 5 4 5 1 2))
'(2 5 4 1)
这篇关于如何摆脱列表中的重复项,但保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!