The loop Macro

loop is a powerful DSL. Alternatives: the iterate library ((iter (for x in list) (collect x)), extensible and Lisp-like) and for. Many Lispers also use mapcar/reduce for simple cases.

;; Counting
(loop for i from 1 to 5 collect i)                 ; (1 2 3 4 5)
(loop for i from 0 below 10 by 2 collect i)        ; (0 2 4 6 8)
(loop for i from 10 downto 1 by 3 collect i)       ; (10 7 4 1)
(loop repeat 3 collect :x)                         ; (:X :X :X)

;; Iterating over collections
(loop for x in '(1 2 3) collect (* x x))           ; (1 4 9)
(loop for x across #(1 2 3) sum x)                 ; 6
(loop for (a b) in '((1 2) (3 4)) collect (+ a b)) ; (3 7): destructuring
(loop for tail on '(1 2 3) collect tail)           ; ((1 2 3) (2 3) (3))
(loop for c across "hello" count (find c "aeiou")) ; 2
(loop for k being the hash-keys of ht using (hash-value v) collect (list k v))
(loop for (key value) on '(:a 1 :b 2) by #'cddr collect key)   ; (:A :B): plist keys

;; Accumulation
(loop for x in '(3 1 4 1 5) maximize x)            ; 5
(loop for x in '(3 1 4) minimize x)                ; 1
(loop for x in '(1 2 3) sum x into total finally (return (/ total 3)))   ; 2
(loop for x in '(1 2 3 4) when (evenp x) collect x into evens
      else collect x into odds
      finally (return (values evens odds)))        ; (2 4), (1 3)
(loop for x in '((1 2) (3)) append x)              ; (
…