问题描述
我需要在LISP中创建一个递归方法,该方法采用列表中的数字并求和.列表中所有非数字的内容都将被跳过(例如,如果列表中包含"Cheese 12 Dog 8 Shoe 5",则输出为25).
I need to create a recursive method in LISP that takes the numbers in a list and finds the sum. Anything in the list that is not a number is skipped (For example, if the list contains "Cheese 12 Dog 8 Shoe 5", the output would be 25).
现在,我的代码找到了总和,但是如果列表中没有数字,则抛出错误.什么可以更改以解决此问题?
Right now my code finds the sum, but throws an error if there is anything in the list that is not a number. What can be changed to fix that?
(defun adder (lis)
(cond
((null lis) 0)
(t (eval (cons '+ lis)) )
)
)
推荐答案
这可以做到:
(defun adder (lis)
(if (null lis)
0
(let ((c (car lis)))
(if (numberp c)
(+ c (adder (cdr lis)))
(adder (cdr lis))))))
您的版本不是递归的(您不会在加法器内部调用加法器),也许您的意思是这样的(非递归的)?
Your version is not recursive (you don't call adder inside of adder), maybe you meant something like this (which is non-recursive)?
(defun adder (lis)
(apply '+ (remove-if-not 'numberp lis)))
这篇关于忽略列表中的非数字值并找到求和递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!