Reputation: 63
The usual and
and or
operators in Common Lisp will lazily evaluate their operands, e.g. the and
will stop once it encounters the first nil
. I am searching for an operator that does not work this way, but instead always evaluates all operands before returning a result. Is there something like this?
In C for example you have the lazy &&
and you have the bitwise &
, which can be used as a non-lazy alternative.
I know about logand
and bit-and
, but those do not work on boolean operands.
E.g.:
(and NIL (not-defined))
would not throw an error, but i want it to throw one.
Upvotes: 5
Views: 337
Reputation: 38924
Alternative implementation for and*
:
(defun and* (&rest values &aux (res t))
(every (lambda (v) (setf res v)) values)
res)
This returns the last non-nil value or nil
.
Upvotes: 1
Reputation: 139381
(defun and* (&rest l)
(every #'identity l))
or returning the last value if all true
(defun and& (&rest l)
(or (null l)
(loop for b in l
unless b
do (return nil)
finally (return b))))
or
(defun and& (&rest l)
(or (null l)
(loop for b in l
always b
finally (return b))))
Upvotes: 3
Reputation: 114579
A possible implementation is
(defun and* (&rest x)
(let ((res T))
(dolist (item x)
(if (null item) (return-from and* item))
(setf res item))
res))
Explanation:
T
(this is needed because (and)
→T
)NIL
then we return itThe implementation of or*
is simpler because the only "falsy" value in Common Lisp is NIL
so there's no need to remember what is the last falsy element and you can just use some
...
(defun or* (&rest x)
(some #'identity x))
Upvotes: 2