Tim
Tim

Reputation: 63

Are there non-lazily evaluated "and" or "or" operations in Common Lisp?

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

Answers (3)

coredump
coredump

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

Rainer Joswig
Rainer Joswig

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

6502
6502

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:

  • We initialize the result to T (this is needed because (and)T)
  • We loop over the arguments
  • If an argument is NIL then we return it
  • Otherwise we store the item as result
  • If we get to the end of the loop then we return last item

The 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

Related Questions