gpt4 book ai didi

Scheme 编写一个函数,返回列表中的奇数个数

转载 作者:行者123 更新时间:2023-12-02 04:59:40 27 4
gpt4 key购买 nike

我在 Scheme 中编写一个函数时遇到问题,该函数在不使用任何赋值语句的情况下返回列表中奇数的数量。我正在尝试使用谓词 odd?以及。任何帮助/提示将不胜感激。

Ex: (odds '(1 2 3 4 5)//返回 3

此外,列表是整数

最佳答案

好吧,如果不能使用赋值语句,您仍然可以为此使用内置过程。特别是,count将在 Racket 中很好地工作:

(define (odds lst)
(count odd? lst))

...但我猜您应该从头开始实现该解决方案。一些自行寻找解决方案的提示,填空:

(define (odds lst)
(cond (<???> ; if the list is empty
<???>) ; then how many odd numbers are in it?
((odd? <???>) ; if the first element is odd
(<???> (odds <???>))) ; then add one and advance recursion
(else ; otherwise
(odds <???>)))) ; just advance the recursion

无论如何,它按预期工作:

(odds '(1 2 3 4 5))
=> 3

关于Scheme 编写一个函数,返回列表中的奇数个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305086/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com