Next: , Previous: , Up: End-Test Control   [Contents][Index]


15.25.7.2 always-never-thereis

always expr
never expr
thereis expr
always

takes one form and terminates the loop if the form ever evaluates to nil; in this case, it returns nil. Otherwise, it provides a default return value of ‘t’.

never

takes one form and terminates the loop if the form ever evaluates to non-nil; in this case, it returns nil. Otherwise, it provides a default return value of ‘t’.

thereis

takes one form and terminates the loop if the form ever evaluates to non-nil; in this case, it returns that value.

Since ‘always’, ‘never’, and ‘thereis’ use the Common Lisp macro return to terminate iteration, any ‘finally’ clause that is specified is not evaluated.

Examples

;;; Make sure I is always less than 11 (two ways).
;;; The FOR construct terminates these loops.
(loop for i from 0 to 10
      always (< i 11))
(loop for i from 0 to 10
      never (> i 11))
;;; If I exceeds 10, return I; otherwise, return NIL.
;;; The THEREIS construct terminates this loop.
(loop for i from 0
      thereis (when (> i 10) i) )
;;; The FINALLY clause is not evaluated in these examples.
(loop for i from 0 to 10
      always (< i 9)
      finally (print "you won't see this"))
(loop never t
      finally (print "you won't see this"))
(loop thereis "Here is my value"
      finally (print "you won't see this"))
;;; The FOR construct terminates this loop,
;;; so the FINALLY clause is evaluated.
(loop for i from 1 to 10
      thereis (> i 11)
      finally (print i)) ;Prints 1 line
(defstruct mountain height difficulty (why "because it is there"))
(setq everest (make-mountain :height '(2.86e-13 parsecs)))
(setq chocorua (make-mountain :height '(1059180001 microns)))
(defstruct desert area (humidity 0))
(setq sahara (make-desert :area '(212480000 square furlongs)))
;First there is a mountain, then there is no mountain, then there is ...
(loop for x in (list everest sahara chocorua) ; -GLS
      thereis (and (mountain-p x) (mountain-height x)))
;;; If you could use this code to find a counterexample to
;;; Fermat's last theorem, it would still not return the value
;;; of the counterexample because all of the THEREIS clauses
;;; in this example return only T.   Of course, this code has
;;; never been observed to terminate.

(loop for z upfrom 2
      thereis
        (loop for n upfrom 3 below (log z 2)
              thereis
                (loop for x below z
                      thereis
                        (loop for y below z
                              thereis (= (+ (expt x n)
                                            (expt y n))
                                         (expt z n))))))

Next: loop-finish Macro, Previous: while-until, Up: End-Test Control   [Contents][Index]