2013-03-09 124 views
-1

标题几乎可以告诉所有事情。检查列表是否包含至少一个非零元素

我正在寻找类似

(atleastonenonnil '(nil nil nil nil '(A B C))) 
=> T 

我可以在一个递归的方式做到这一点,但我不能。我应该使用一些内置功能吗? 我正在使用cLisp

+4

http://www.lispworks.com/documentation/HyperSpec/Body/f_everyc.htm#some – 2013-03-09 18:29:53

+0

我会接受该评论作为答案 – Simbi 2013-04-06 07:47:59

回答

2

如果您处理列表的第一个元素,那么其余所有内容都可以递归执行。代码是这样的:

(defun at-least-one-nonnil (l) 
    (and (not (nullp l)) 
     (or (car l) 
      (at-least-one-nonnil (cdr l)))))) 

当然在这种简单的情况下,已经有一个内置函数。

(defun at-least-one-nonnil-v2 (l) 
    (some #'identity l)) 

但这并不能帮助你了解递归。

+1

这两个函数实际上是不是至少一个零?为了得到所需的行为,你应该放弃最后一个函数的最后一个,并且用'#'identity'代替'#'not'。此外,Common Lisp使用'(defun function(args)...)'而'(define(function args)...)'是scheme。 – 2013-03-10 14:11:01

相关问题