如何删除列表方案中的所有重复元素?
我的尝试是,
(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))))
)
)
我的列表是(abcaaccc)
我想要的是(abc)
。有什么想法吗?
谢谢,
My attempt was,
(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))))
)
)
My list was (a b c a a c c c )
What I want is (a b c)
. Any idea?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将通过循环使用由可见元素构建的第二个列表来解决此问题。如果这是家庭作业,我会为给你这个而感到难过 - 理解递归的工作原理比仅仅得到正确的答案更重要。
更新以适应您的评论 - 这可能不是最干净的解决方案,但应该让您了解它的工作原理。
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.
Updated to accommodate your comments - this probably isn't the cleanest solution but should give you an idea of how it might work.
R5RS+SRFI1
R5RS + SRFI1
使用 SRFI 1,您可以直接使用
delete-duplicates
或delete-duplicates!
:http://srfi.schemers.org/srfi-1/srfi-1.html#delete-duplicatesUsing SRFI 1 you can use directly
delete-duplicates
ordelete-duplicates!
: http://srfi.schemers.org/srfi-1/srfi-1.html#delete-duplicates