gpt4 book ai didi

方案 - 计算列表中的元素

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

我有以下代码:

(define (howMany list)
(if (null? list)
0
(+ 1 (howMany (cdr list)))))

如果我们执行以下操作:(howMany '(1 2 3 (4 5))) 我们将得到 4 作为结果。我该如何做才能计算列表中的整数数量。这意味着相同的问题将返回 5 作为答案,而不是 4。

最佳答案

您只需使用标准模板来遍历列表列表:

(define (howMany lst)
(cond ((null? lst) 0) ; an empty list has 0 elements
((not (pair? lst)) 1) ; if it's an element, then count it as 1
(else (+ (howMany (car lst)) ; otherwise advance the recursion
(howMany (cdr lst)))))) ; over both the `car` and the `cdr`

更短、更惯用的解决方案是使用内置列表过程,如下所示:

(define (howMany lst)
(length (flatten lst)))

无论哪种方式,它都会按预期工作:

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

关于方案 - 计算列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425967/

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