Tutorial for the Common Lisp Loop Macro

Peter D. Karp
SRI International
pkarp @ ai.sri.com

The Loop Macro is one of the most valuable, and least-well documented
of the operations in Common Lisp. It is valuable because it is
more powerful, more compact, and more readable than comparable Common Lisp
constructs such as mapping operations and recursion. It also uses a
programming style that will be familiar to programmers who have worked
with other more traditional languages. This short guide
provides examples of how to use the Loop Macro.

The Loop macro is different than most Lisp expressions in having a
complex internal syntax that is more similar to programming
languages like C or Pascal. So you need to read Loop expressions with
half of your brain in Lisp mode, and the other half in Pascal mode.

Think of Loop expressions as having four parts: expressions that set
up variables that will be iterated, expressions that conditionally
terminate the iteration, expressions that do something on each
iteration, and expressions that do something right before the Loop
exits. In addition, Loop expressions can return a value. It is very
rare to use all of these parts in a given Loop expression, but you can
combine them in many ways.