Reading — step 1 of 5
Learn
~1 min readIteration and Macros
loop is Common Lisp's iteration powerhouse — practically a mini-language.
Counting:
(loop for i from 1 to 10
do (print i))
(loop for i from 10 downto 1 by 2
do (print i))
Iterating over collections:
(loop for x in '(a b c d)
do (print x))
(loop for x across #(1 2 3) ; vector
do (print x))
(loop for x being the hash-keys of ht
do (print x))
Collecting results:
(loop for n from 1 to 5
collect (* n n)) ; (1 4 9 16 25)
(loop for n in '(1 2 3 4 5)
when (evenp n)
collect (* n n)) ; (4 16)
Accumulators:
collect— build a listsum/count/maximize/minimizenconc— destructive list concat
(loop for n in '(1 2 3 4 5) sum n) ; 15
(loop for n in '(1 2 3 4 5)
when (evenp n) count n) ; 2
Multiple iterators:
(loop for x in '(a b c)
for y in '(1 2 3)
collect (list x y)) ; ((a 1) (b 2) (c 3))
Conditions:
(loop for n from 1 to 100
while (< n 50)
sum n)
(loop for n from 1
until (> n 100)
do (print n))
loop reads almost like English. There's also a do macro (more parens, less English) and dolist/dotimes for simple cases.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…