以下递归函数的非递归函数是什么?
问题描述:
(defun filter-numbers-rec (inlist)
"This function filters out non-numbers from its input list and returns
the result, a list of numbers"
(cond
((not (listp inlist))
(princ "Argument must be a list")
(terpri)
())
((null inlist)
())
((not (numberp (car inlist)))
(filter-numbers-rec (cdr inlist)))
(t
(cons (car inlist)
(filter-numbers-rec (cdr inlist))))))
答
好,功能所做的说明是要从列表中删除每一件事情如果是不是一些,所以一个很好的候选人这里是remove-if-not
,你会使用方法如下:
(remove-if-not 'numberp '(1 a 2 b 3 C#\x (y 4)))
;=> (1 2 3)
如果由于某种原因,你想要的方式,(可能)不使用递归,你可以用它来写这个do
:
(do ((list '(1 a 2 b 3 C#\x (y 4)) (rest list))
(result '()))
((endp list) (nreverse result))
(when (numberp (car list))
(push (car list) result)))
;=> (1 2 3)
如果你不喜欢的do
的赘言,你可以使用loop
:
(loop :for x :in '(1 a 2 b 3 C#\x (y 4))
:when (numberp x)
:collect x)
;=> (1 2 3)