【问题标题】:Common Lisp: all or any elements are true in a listCommon Lisp:列表中的所有或任何元素都为真
【发布时间】:2023-04-05 17:34:01
【问题描述】:

在 Python 中有函数 allany 如果列表的所有或部分元素分别为真,则它们返回真。 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 宏与 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
      

      【讨论】:

        猜你喜欢
        • 2016-03-23
        • 1970-01-01
        • 2012-12-15
        • 2019-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-13
        • 1970-01-01
        相关资源
        最近更新 更多