方案中的偶数总和
这是我第一次接触Scheme。我有一个包含整数的列表,我想获得列表中所有偶数的总和。
; sum_even
(define (sum_even l)
(if (null? l) l
(cond ((even? (car l)) 0)
((not(even? (car l))) (car l)))
(+ (sum_even (car l) (sum_even(cdr l))))))
(sum_even '(2 3 4))
This is my first experience with Scheme. I have a list with integers and I wanna get the sum of all even number in list.
; sum_even
(define (sum_even l)
(if (null? l) l
(cond ((even? (car l)) 0)
((not(even? (car l))) (car l)))
(+ (sum_even (car l) (sum_even(cdr l))))))
(sum_even '(2 3 4))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
未测试
Not tested
你并不是在问一个问题。您是否正在检查您的解决方案是否正确或正在寻找替代解决方案?
您还可以通过编辑实现它,如下所示
:如果正如您所提到的,您不能使用过滤器,则此解决方案将起作用并且是尾递归的:
You're not exactly asking a question. Are you checking if your solution is correct or looking for an alternate solution?
You can also implement it as follows via
edit: If, as you mentioned, you can't use filter, this solution will work and is tail-recursive:
例子:
Example:
这是另一个具有高阶函数并且没有显式递归的函数:
Here is another one with higher order functions and no explicit recursion:
考虑使用内置过滤器功能。例如:
将返回列表l中偶数的列表。有很多方法可以对列表中的数字求和(示例取自 http://groups.engin.umd.umich.edu/CIS/course.des/cis400/scheme/listsum.htm):
Consider using the built-in filter function. For example:
will return a list of even numbers in the list l. There are lots of ways to sum numbers in a list (example taken from http://groups.engin.umd.umich.edu/CIS/course.des/cis400/scheme/listsum.htm):