並行迭代
在 LOOP
中允許多個 FOR
條款。當第一個子句結束時,迴圈結束:
(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))
確定迴圈是否應該繼續的其他子句可以組合使用:
(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)
確定哪個列表更長,一旦知道答案就切斷迭代:
(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)))
編號列表的元素:
(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))
確保列表中的所有數字均勻,但僅適用於前 100 個專案:
(assert
(loop for number in list
repeat 100
always (evenp number)))