我有以下代码:
(define (howMany list)
(if (null? list)
0
(+ 1 (howMany (cdr list)))))
Run Code Online (Sandbox Code Playgroud)
如果我们执行以下操作:(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`
Run Code Online (Sandbox Code Playgroud)
一个更短、更惯用的解决方案是使用内置列表过程,如下所示:
(define (howMany lst)
(length (flatten lst)))
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,它都会按预期工作:
(howMany '(1 2 3 (4 5)))
=> 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7130 次 |
| 最近记录: |