计算列表结构中的原子 [英] Count atoms in a list structure
问题描述
我需要找到一个给定输入有多少个元素.输入可以是列表或符号,例如:
I need to find how many elements a given input has. the input can be a list or a symbol, for example:
-
'a
=> 1个元素 -
'(3 . 4)
=> 2个元素 -
'(a b . c)
=> 3个元素 -
'((a b . c) 3 . 4)
=> 5个元素
'a
=> 1 element'(3 . 4)
=> 2 elements'(a b . c)
=> 3 elements'((a b . c) 3 . 4)
=> 5 elements
一个问题是,当我浏览输入时,每个元素都可以是其自己的列表,也可以是一对(刚刚开始学习的方案,所以我现在使用的工具主要是car/cdr),所以,我什么时候应该停止循环? if (null? x)
条件为真时?还是if (null? (car x))
为true时?
one problem is that when I'm going through the input, every element can be a list of its own, or a pair (just started learning scheme, so my tools for right now are mainly car/cdr), so, when should I stop my loop? when if (null? x)
condition is true? or maybe when if (null? (car x))
is true?
推荐答案
问题的标题应该是如何更改列表结构中原子的计数.关于SE,有很多关于它的问题. 方法如下:
The title of your question should be changes to how to count atoms in a list structure. There are numerous questions on SE about it. Here is how:
- 如果元素是一对,则结果将是应用于同一过程的
car
和cdr
之和. - 其他长度为
1
- if element is a pair, the result would be the sum of the
car
and thecdr
applied to the same procedure. - else the length is
1
编辑
以下是上述算法的代码:
Here's the above algorithm as code:
(define (count-all-atoms x)
(if (pair? x)
(+ (count-all-atoms (car x))
(count-all-atoms (cdr x)))
1))
要评论我所得到的评论,实际上还有2种方法可以实现此目的,所有这些方法都将为OP的示例提供正确的答案.一切都与我们解释()
的方式有关.
To comment the comments I've got there are actually 2 more ways to implement this and all of them will give the correct answer to OP's examples. It all has to do with how we interpret ()
to be.
取决于'(())
的情况应计为0、1或2个元素.因为它是所有没有原子的列表,所以为零;由于它的一个列表带有一个空元素(不计算空终止符),所以为1;或者因为它与带有两个空元素的点对((() ())
)相同,所以为2.这是我的文字描述的最后一个方法,但这是另外两种方法:
Depending on '(())
should be counted as 0, 1 or 2 elements. Zero since it's all lists without any atoms, 1 since its one list with one null element (not counting null terminator) or 2 since it's the same as a dotted pair with two null elements ((() ())
). It's the last one that my text described, but here are the two other ways:
;; count (()) and () as 0
;; no nil value is counted as it is a list without elements
(define (count-non-nil-atoms x)
(if (pair? x)
(+ (count-non-nil-atoms (car x))
(count-non-nil-atoms (cdr x)))
(if (null? x)
0
1)))
;; count (()) as 1 and () as 0
;; ie. count only nil as atom in car position but not as a list terminator
;; probably most common
(define (count-atoms x)
(if (pair? x)
(let ((a (car x)) (d (cdr x)))
(+ (if (null? a) 1 (count-atoms a))
(count-atoms d)))
(if (null? x) 0 1)))
这篇关于计算列表结构中的原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!