Common Lisp:列表中的所有或任何元素都是真的

时间:2012-12-18 19:30:07

标签: python list lisp common-lisp

在Python中,有函数allany如果列表的所有或部分元素分别为true,则返回true。 Common Lisp中是否有相同的功能?如果没有,最简洁和惯用的方式是什么?

目前我有这个:

(defun all (xs)
  (reduce (lambda (x y) (and x y)) xs :initial-value t))

(defun any (xs)
  (reduce (lambda (x y) (or x y)) xs :initial-value nil))

2 个答案:

答案 0 :(得分:29)

在Common Lisp中,使用every(相当于all)和some(相当于any)。

答案 1 :(得分:6)

您可以将LOOP宏与ALWAYSTHEREIS条款一起使用,如下所示:

CL-USER 1 > (loop for item in '(nil nil nil) always item)
NIL

CL-USER 2 > (loop for item in '(nil nil t) always item)
NIL

CL-USER 3 > (loop for item in '(t t t) always item)
T

CL-USER 4 > (loop for item in '(nil nil nil) thereis item)
NIL

CL-USER 5 > (loop for item in '(nil nil t) thereis item)
T

CL-USER 6 > (loop for item in '(t t t) thereis item)
T
相关问题