嵌套列表LISP中数字元素的总和



使用LISP返回嵌套列表中数字元素的总和。如果没有数字元素,则返回空列表/NIL

示例:

(6 3 -2 5 (4 2 -3) 4) should return 19

(1 2 3 (-4 5) a b c) should return 7

让别人帮你做作业几乎从来都不是学习任何东西的好方法。

但这里有一个答案,它是用Lisp(Racket(写的,它确实展示了你应该如何解决这个问题,而且(我认为(展示了一些思考这样问题的好方法。。。但你几乎肯定不会剪切粘贴。

请注意,这并不完全符合给定的要求:它应该为一个没有数字的列表返回一个非数字值。这打破了这样的递归算法,因为空列表是一个没有数据的列表。所以这做了一些更明智的事情。让这个答案实现要求是留给学生的练习。

(define (sum-nested-list l)
(let sum-nested-list-loop ([thing l]
[running-total 0])
(match thing
['()
;; We're done if we've run out of list
running-total]
[(list* (? number? x) r)
;; A list whose first element is a number: add it to the running total
;; and carry on on the rest of the list
(sum-nested-list-loop r (+ running-total x))]
[(list* (? list? x) r)
;; A list whose first element is a nested list: recurse into the
;; nested list
(sum-nested-list-loop r (sum-nested-list-loop x running-total))]
[(list* _ r)
;; A list whose first element is not a number or a nested list:
;; carry on on the rest of the list
(sum-nested-list-loop r running-total)]
[_
;; Not a list at all: explode
(error 'sum-numeric-list "what?")])))
(defun flat-sum (tree)
(let ((count 0))
(tree-equal tree tree :test (lambda (left right)
(if (numberp left)
(incf count left) t)))
count))
1> (flat-sum '(1 2 3 (-4 5) a b c))
7

相关内容

最新更新