计算列表中正元素的数量
我正在尝试计算列表中积极元素的数量。这是我到目前为止所得到的:
(define howMany
(lambda (list)
(cond
[(not (list? list)) 0]
[(null? list) 0]
[(> list 0) (+ 1 (howMany (cdr list)))])))
它一直给我一个错误,“需要输入实数”,你将如何解决这个问题?
哦,我这样称呼它:
(howMany '(6 7 8))
Im trying count the number of positive elements in a list. Here is what I have so far:
(define howMany
(lambda (list)
(cond
[(not (list? list)) 0]
[(null? list) 0]
[(> list 0) (+ 1 (howMany (cdr list)))])))
It keeps giving me an error, "expects type real number", how would you fix this?
Oh im calling this like so:
(howMany '(6 7 8))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能指望
(> list 0)
起作用 —list
是一个列表,但>
期望其参数为数字。您想要查看列表的第一个元素是否为正,因此应该为
(> (car list) 0)
。但是:您的代码存在一个更大的问题:如果第一个元素为负数或零,会发生什么?
You can't expect
(> list 0)
to work —list
is a list, but>
expects its arguments to be numbers.You want to see if the first element of the list is positive, so that should be
(> (car list) 0)
.However: there's a bigger problem with your code: what happens if the first element is negative or zero?
您的代码中有几个错误。
(> list 0)
应为(> (car list) 0)
因为您要检查列表的第一个元素大于 0。您也不能将>
的默认实现应用于列表。(+ 1 (howMany (cdr list)))
也会失败,因为howMany
并不总是计算为数字。您必须通过将计数器作为参数传递给递归调用的过程来维护计数器。一种方法是:测试:
There are a couple of bugs in your code.
(> list 0)
should be(> (car list) 0)
as you want to check if the first element of the list is greater than 0. You cannot apply the default implementation of>
to a list either.(+ 1 (howMany (cdr list)))
will also fail ashowMany
does not always evaluate to a number. You have to maintain a counter by passing that as an argument to the recursively called procedure. One way to do this is:Test:
这是您的问题:
(> list 0)
您正在将列表与数字进行比较。尝试
(> (length list) 0)
或(not (null? list))
。或者无论“cond 块中的默认条件”的Scheme 关键字是什么。编辑:这就是当您首先关注错误消息时您会得到的结果。加雷斯当然是对的。
Here's your problem:
(> list 0)
You're comparing a list to a number. Try
(> (length list) 0)
or(not (null? list))
. Or whatever the Scheme keyword for "default condition in acond
block" is.Edit: This is what you get when you focus on error messages foremost. Gareth has it right, of course.
我将使用的递归算法的伪代码。
我不知道Scheme 或Clojure (你的方括号让我想起了)。
或者你可以用 Common Lisp 编写一个相当时髦的应用方法——额外的换行符以提高可读性。
Pseudocode for the recursive algorithm I would use.
I don't know either Scheme or Clojure (which your square brackets remind me of).
Or you could write a considerably snazzier applicative approach in Common Lisp- extra newlines for readability.