计算Scheme中的唯一元素
编写一个递归Scheme过程count-dist elements,它接受一个包含重复元素的列表,并返回列表中不同元素的数量。
这是我的代码,但它无法正常工作。请帮忙!谢谢!!
(define (count-dist-elements lis)
(cond
((null? lis) 0)
((null? (cdr lis))0)
((member (car lis)(cdr lis)))
(else(+ 1(count-dist-elements (cdr lis))))))
p/s: 就这样吧 (count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9))
Write a recursive Scheme procedure count-dist elements that takes a list with duplicate elements and returns the number of distinct elements in the list.
This is my code, but it is not working correctly. Please help! Thanks!!
(define (count-dist-elements lis)
(cond
((null? lis) 0)
((null? (cdr lis))0)
((member (car lis)(cdr lis)))
(else(+ 1(count-dist-elements (cdr lis))))))
p/s: let it be (count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来你已经很接近了。
(5 5)
)怎么样?你的函数返回一个合理的值吗?It looks like you're getting pretty close.
(5 5)
)? Does your function return a sensible value?第一:为什么在
(null? (cdr lis))
情况下返回零?第二:如果第一个元素也出现在列表的后面,您认为您的代码会返回什么?你确定吗?
First: Why are you returning zero in the
(null? (cdr lis))
case?Second: What do you think your code returns in the case where the first element also occurs later in the list? Are you sure?
(count-dist-elements '(abbc) '() 0)
==>;3
(count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9) '() 0)
==>9
或者,如果您希望它递归而不是迭代(并且它必须使用如图所示的函数调用),
则会给出相同的结果。
(count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9))
==>; <代码>9(count-dist-elements '(a b b c) '() 0)
==>3
(count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9) '() 0)
==>9
Or, if you want it recursive and not iterative (and, it has to use a function call like the one shown),
Gives the same results.
(count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9))
==>9