Marty Hall's Thumbnail Summary Of LOOP Syntax


Basic Structure:

(1) (loop for I from N1 to N2 do ...)

Also by and downto variations

(2) (loop for Entry in List do ...)

(3) (loop repeat X do ...)

(4) (loop until Condition do ...)

(5) (loop while Condition do ...)


(1A) (loop for I from 1 to 3 do (print I)) 1 2 3 NIL ; NIL is value returned by loop
(1B) (loop for I from 1 to 5 by 2 do (print I)) 1 3 5 NIL
(2) (loop for Entry in '(A B C) do (print Entry)) A B C ==> NIL
(3) (loop repeat 2 do (print "Hello")) "Hello" "Hello" ==> NIL
(4) (setq X 10) (loop until (> X 12) do (setq X (+ X 1)) (print X)) 11 12 13 ==> NIL
(5) (setq X 10) (loop while (<= X 12) do (setq X (+ X 1)) (print X)) 11 12 13 ==> NIL

WITH

Declares variables local to the loop.

(setq X 7)
(loop with (X)
  for I from 1 to 5 do
    (setq X (* I I))
    finally (return X))
==> 25       ; the value of the local X
X ==> 7      ; the global X unaffected

FINALLY and RETURN:

RETURN breaks out of the loop at any point, returning a value as the result of the LOOP form. FINALLY specifies what to do once the LOOP form is done, usually used to specify a return value.

(loop for I from 1 to 10 do
 (print I)
 (if (> I 2) (return "Done")) )
1
2
3
==> "Done" 

(let ((Total 0)) (loop for I from 1 to 4 do (setq Total (+ Total I)) finally (return Total))) ==> 10

NOTE: As in most languages, be careful of returning the local variable, since it is incremented before the termination test. E.g.

(loop for I from 1 to 3 do
 (print I)
   finally
 (return (* I I)))
1
2
3
==> 16 ; Return value (not 9!)

COLLECTING and SUMMING

COLLECTING creates a list and returns it as the value of the loop. SUMMING adds up a total and returns it as the value of the loop


(loop for I from 1 to 5 collecting (* I I)) ==> (1 4 9 16 25)
(loop for I from 1 to 5 summing (* I I)) ==> 55

DOLIST and DOTIMES

These simpler iteration constructs were widely used before LOOP was added to the language, and still appear in some code.


(dotimes (I Number) <Body>) is like (loop for I from 0 to (- Number 1) do <Body>)
(dolist (Entry List) <Body>) is like (loop for Entry in List do <Body>) (dolist (Entry '(A B C)) (print Entry)) A B C ==> NIL

Table of contents

Basic Structure:
WITH
FINALLY and RETURN:
COLLECTING and SUMMING
DOLIST and DOTIMES