从方案中的列表中删除所有重复成员 [英] Removing all duplicate members from a list in scheme

查看:28
本文介绍了从方案中的列表中删除所有重复成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用递归删除列表中的重复项.这就是我所拥有的.它只删除第一个重复项,而不是全部.

I am trying to remove duplicates in a list, using recursion. This is what I have. It only removes the first duplicate, not all of them.

我的想法是查看第一个成员,检查它是否是列表其余部分的成员,如果是,则再次调用该函数.如果没有,请创建一个包含第一个成员和再次调用该函数的结果的列表.我不明白为什么它不删除所有重复项.

My idea is to look at the first member, check if its a member of the rest of the list, if so, call the function again. If not, create a list with the first member and the result from calling the function again. I don't understand why it doesn't remove all the duplicates.

(define (removeDupes L)
  (cond ((null? L) ())
        ((list? (member (car L) (cdr L))) removeDupes (cdr L))
        (#T (cons ((car L) (removeDupes (cdr L)))))))

这是我修改后的样子,它有效!!我明白缺点有什么问题.它需要两个参数,我只给了它一个.我仍然不知道为什么第三行不起作用......

This is what I modified it to, and it works!! And I understand what was wrong with the cons. It needs two parameters and I only gave it one. I still have no Idea why the third line did not work....

(define (removeDupes L)
  (cond ((null? L) ())
        ((list? (member (car L) (cdr L)))(removeDupes(cdr L)))
        (#T (cons (car L) (removeDupes (cdr L))))))

推荐答案

您的代码中有多个错误,但可能导致您在此处报告的问题的一个错误是第三行中的括号错误.您正在尝试调用 removeDupes 但您的代码实际上并没有这样做;相反,这种情况下的值最终是 (cdr L).你能明白为什么吗?

There are multiple errors in your code, but the one that's probably causing the problem you've reported here is that your parentheses are wrong in the third line. You're trying to call removeDupes but your code doesn't actually do so; instead the value in that case ends up being (cdr L). Can you see why?

修复此问题后,您会发现您的代码开始产生错误.对于您可能首先遇到的问题:仔细查看您是如何在最后一行调用 cons 的.对于您接下来可能会遇到的问题:请记住,() 在 Scheme 中不是自我评估的.

When you fix this, you'll find that your code starts producing errors. For the one you're likely to encounter first: take a careful look at how you're invoking cons on the last line. For the one you're likely to encounter next: remember that () is not self-evaluating in Scheme.

(我认为如果你注意代码的间距和布局,这种事情就更难错过了.例如,在每个列表的元素之间放置空格.直到你对这些东西非常熟悉,以至于这些错误不再发生,您可能希望养成在遇到神秘错误时检查括号的习惯:是否错过了表达式开头的 ( ,或添加了额外的 ( 在函数的参数之前,或者忘记了 cond 子句周围的额外级别的括号,等等等等等等.别担心:过一段时间它会停止正在发生……)

(I think this sort of thing is much harder to miss if you take care with the spacing and layout of your code. Put spaces between the elements of every list, for instance. Until you get so familiar with this stuff that these mistakes stop happening, you might want to make a habit of checking the parentheses any time you run across a mysterious error: have you missed a ( at the start of an expression, or put an extra ( before the arguments of a function, or forgotten the extra level of parens round a cond clause, or etc. etc. etc. Don't worry: after a while it'll stop happening...)

这篇关于从方案中的列表中删除所有重复成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆