Multiple FOR
clauses are allowed in a LOOP
. The loop finishes when the first of these clauses finishes:
(loop for a in '(1 2 3 4 5)
for b in '(a b c)
collect (list a b))
;; Evaluates to: ((1 a) (2 b) (3 c))
Other clauses that determine if the loop should continue can be combined:
(loop for a in '(1 2 3 4 5 6 7)
while (< a 4)
collect a)
;; Evaluates to: (1 2 3)
(loop for a in '(1 2 3 4 5 6 7)
while (< a 4)
repeat 1
collect a)
;; Evaluates to: (1)
Determine which list is longer, cutting off iteration as soon as the answer is known:
(defun longerp (list-1 list-2)
(loop for cdr1 on list-1
for cdr2 on list-2
if (null cdr1) return nil
else if (null cdr2) return t
finally (return nil)))
Numbering the elements of a list:
(loop for item in '(a b c d e f g)
for x from 1
collect (cons x item))
;; Returns ((1 . a) (2 . b) (3 . c) (4 . d) (5 . e) (6 . f) (7 . g))
Ensure that all the numbers in a list are even, but only for the first 100 items:
(assert
(loop for number in list
repeat 100
always (evenp number)))