Common Lisp: all or any elements are true in a list
Asked Answered
S

2

17

In Python there are functions all and any they return true if all or some elements of a list are true respectively. Are there equivalent functions in Common Lisp? If not, what is the most succinct and idiomatic way to write them?

Currently i have this:

(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))
Severance answered 18/12, 2012 at 19:30 Comment(0)
D
31

In Common Lisp, use every (that's the equivalent of all) and some (that's the equivalent of any).

Doubletalk answered 18/12, 2012 at 19:34 Comment(0)
T
6

You can use the LOOP macro with ALWAYS and THEREIS clauses like this:

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
Thrippence answered 18/12, 2012 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.