Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Syntax and Evaluation

Iteration with loop and do

Repeat work in Common Lisp using dotimes, dolist, do and the powerful loop macro with for, collect, sum, when, while, and early exit with return.

Lisp offers several ways to repeat work. Simple counted and list loops use dotimes and dolist. The general low-level loop is do. For most real work you will use loop, a macro with its own readable mini-language. This lesson covers all of them, shows how to exit early, and ends with a runnable stand-in for loop so you can see how its clauses combine.

dotimes: repeat n times

LISP
(dotimes (i 3)
  (format t "i = ~a~%" i))
;; i = 0
;; i = 1
;; i = 2

(dotimes (var count result) body) runs the body with var going from 0 up to count - 1. The optional result form is evaluated at the end and its value is returned (default NIL).

LISP
(let ((sum 0))
  (dotimes (i 5 sum)       ; returns SUM when finished
    (incf sum i)))         ; => 10

dolist: walk a list

LISP
(dolist (colour '(red green blue))
  (format t "~a~%" colour))
;; RED
;; GREEN
;; BLUE
LISP
(let ((evens '()))
  (dolist (n '(1 2 3 4 5 6) (nreverse evens))   ; result form
    (when (evenp n) (push n evens))))           ; => (2 4 6)

The idiom push + nreverse (reverse at the end) builds a list in order efficiently, because push adds to the front.

Early exit: return

Both dotimes and dolist (and do, loop) wrap their body in a block named NIL, so (return value) exits immediately:

LISP
(dolist (x '(3 8 12 5))
  (when (> x 10)
    (return x)))        ; => 12

do: the general loop

do has variable specs with step forms, an end test with result, and a body:

LISP
(do ((i 0 (1+ i))          ; (var init step)
     (acc '() (cons i acc)))
    ((= i 4) (reverse acc)) ; (end-test result)
  (format t "step ~a~%" i)) ; body
;; prints step 0..3, returns (0 1 2 3)

do steps all its variables in parallel; do* steps them sequentially. It is powerful but terse, so for ordinary loops prefer loop.

The loop macro

Simple loop: with no keywords at all, loop repeats forever until you return:

LISP
(let ((n 0))
  (loop
    (incf n)
    (when (> n 3) (return n))))   ; => 4

Extended loop: as soon as you write keywords, it becomes a small language:

LISP
(loop for i from 1 to 5 collect (* i i))        ; => (1 4 9 16 25)
(loop for x in '(1 2 3 4) sum x)                 ; => 10
(loop for i below 3 do (print i))                ; 0 1 2
(loop for i from 10 downto 7 collect i)          ; => (10 9 8 7)
(loop for i from 0 to 20 by 5 collect i)         ; => (0 5 10 15 20)
(loop repeat 3 collect 'x)                       ; => (X X X)

Clauses: where values come from

Clause Meaning
for i from 1 to 10 Count up, inclusive. below excludes the end
for i from 10 downto 1 Count down
for x in list Each element of a list
for x on list Each tail of a list
for c across vector Each element of a vector or string
for x = expr then expr Any value sequence you define
for k being the hash-keys of table using (hash-value v) Walk a hash table
with x = 0 A local variable initialised once

Clauses: what to do and accumulate

Clause Result
collect expr List of values
sum expr Total
count expr How many times expr was true
maximize expr, minimize expr Biggest, smallest
append expr Concatenate lists
do form... Run forms for effect

Control clauses

LISP
(loop for x in '(1 2 3 4 5 6)
      when (evenp x) collect x)                  ; => (2 4 6)

(loop for x in '(1 2 3 4 5 6)
      unless (evenp x) sum x)                    ; => 9

(loop for i from 1
      while (< (* i i) 50)
      collect i)                                 ; => (1 2 3 4 5 6 7)

(loop for x in '(2 4 6) always (evenp x))        ; => T
(loop for x in '(1 2 3) thereis (and (> x 1) x)) ; => 2

for clauses run in parallel, ending when the shortest sequence ends:

LISP
(loop for x in '(1 2 3)
      for y in '(a b c d)
      collect (list x y))      ; => ((1 A) (2 B) (3 C))

Add finally for a final action or return value:

LISP
(loop for x in '(5 3 9)
      maximize x into biggest
      finally (return (list 'max biggest)))      ; => (MAX 9)

loop is very expressive but can be written into confusing knots. If a loop has many clauses, split it or use functions such as mapcar, reduce, and remove-if from List Functions.

A stand-in for loop

Writing a full loop needs a Lisp compiler, so this JavaScript stand-in models a few clauses (for ... from ... to, for ... in, when, collect, sum) to show how clauses combine. It is not real Lisp, and it is much smaller than the real macro.

JS Stand-in: a miniature loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line shows the real loop behavior of stopping when the shortest for sequence ends.

Loops versus mapping

Idiomatic Lisp often replaces explicit loops with mapping functions, which we meet next chapter:

LISP
(mapcar #'1+ '(1 2 3))              ; => (2 3 4)
(loop for x in '(1 2 3) collect (1+ x))   ; same result

Pick whichever reads better. Use dolist for side effects, loop for accumulations with several clauses, and mapcar/reduce for simple transformations.

Common mistakes

  1. Modifying the list you are iterating over. Collect results into a new list instead.
  2. Forgetting nreverse after push. push builds the list backwards.
  3. Treating zero as false. In when and while tests only NIL is false.
  4. Mixing simple loop and keywords. (loop (print 1) for i ...) is an error.
  5. Off-by-one confusion: to includes the end value; below does not; dotimes stops at n - 1.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (loop for i from 1 to 5 collect (* i i)) return?

    to is inclusive, so i runs 1..5 and collect gathers the squares into a list.
  2. 2. Which form exits a dolist early with a value?

    dolist, dotimes, do and loop establish a block named NIL; (return x) leaves it.
  3. 3. How many times does (dotimes (i 4) ...) run its body?

    i takes the values 0, 1, 2 and 3.
  4. 4. What does (loop for x in '(1 2 3) for y in '(a b) collect (list x y)) return?

    Multiple for clauses step together and the loop ends when the shortest runs out.

Summary

  • dotimes counts from 0, dolist walks a list; both can return a result form and support (return ...).
  • do is the general loop with parallel stepping; do* steps sequentially.
  • loop has a simple form (forever) and an extended form with for, collect, sum, when, while, finally.
  • Several for clauses run in parallel and stop at the shortest.
  • Mapping functions often read better than explicit loops.

Next: Conses and Lists