【问题标题】:Common Lisp: all or any elements are true in a listCommon Lisp:列表中的所有或任何元素都为真
【发布时间】:2023-04-05 17:34:01
【问题描述】:
在 Python 中有函数 all 和 any 如果列表的所有或部分元素分别为真,则它们返回真。 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))
【问题讨论】:
标签:
list
lisp
common-lisp
【解决方案1】:
在 Common Lisp 中,使用every(相当于all)和some(相当于any)。
【解决方案2】:
您可以将 LOOP 宏与 ALWAYS 和 THEREIS 子句一起使用,如下所示:
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