【问题标题】:How to go count all of the atoms in a list (or a list of nested lists) when you use recursion使用递归时如何计算列表(或嵌套列表的列表)中的所有原子
【发布时间】:2019-10-02 17:09:50
【问题描述】:

我正在创建一个计算列表中原子数的递归函数。它应该能够计算嵌套列表的原子。 例如:(a (b c) e d) 或 (a (b c (g e)) e d),它应该分别计算 b 和 c 或 b、c、e 和 d 分别而不是整体。

这是我创建的函数:

(defun  count-atoms (mylist)
    (cond
    ((null mylist) 0)
    ((listp (car mylist)) (count-atoms (car mylist)))
    ((atom (car mylist)) (+ 1 (count-atoms (rest mylist))))
    )
)

我得到的输出是 3,但它应该是 5(基于 (a (b c) e d))。我猜这个函数在它到达 c 的那一刻就停止了。如何使函数不在 c 处停止并使其返回最外层列表。

【问题讨论】:

    标签: recursion lisp common-lisp


    【解决方案1】:

    这是我们可以推断问题的一种方法 -

    • 如果输入是null,则返回零

      '( )
        ^
        | 0 atoms 
      
    • (归纳)否则输入有至少一个元素。如果car 是一个列表,请在car cdr 上调用count-elements。将两个结果相加并返回。

      '( a         b c d ... )
         ^         ^
         |         | count atoms in cdr <-
         |                                \
         | count atoms in sublist   <------\_ add together
      
    • (inductive) 否则输入有至少一个元素不是一个列表。在cdr 上致电count-elements。将结果加一并返回。

      '( a         b c d ... )
         ^         ^
         |         | count atoms in cdr <-
         |                                \
         | one atom      <-----------------\_ add together
      

    你看到你的程序有什么不同吗?

    【讨论】:

    • 如果 car 是列表,我的程序不会添加列表的其余部分?
    • 宾果游戏!你明白了:)
    • 天哪,哈哈!非常感谢你!我修好了它! :D
    【解决方案2】:

    你的错误是你忽略了第二个子句中的尾巴。

    (defun count-atoms (tree)
      "Count atoms in all leaves of the tree, ignoring terminating NIL."
      (if tree
          (+ (if (atom (car tree))
                 1
                 (count-atoms (car tree)))
             (count-atoms (cdr tree)))
          0))
    

    现在

    (count-atoms '(a (b c) e d))
    ==> 5
    (count-atoms '(a (b c (g e)) e d))
    ==> 7
    (count-atoms '(a (b c (g e)) nil e d))
    ==> 8
    

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 2021-01-12
      • 2018-07-25
      • 1970-01-01
      相关资源
      最近更新 更多