Iteration
=========
Iteration means executing part of a program repetitively. For
example, you might want to repeat some computation once for each element
of a list, or once for each integer from 0 to N. You can do this in
Emacs Lisp with the special form `while':
- Special Form: while condition forms...
`while' first evaluates CONDITION. If the result is non-`nil', it
evaluates FORMS in textual order. Then it reevaluates CONDITION,
and if the result is non-`nil', it evaluates FORMS again. This
process repeats until CONDITION evaluates to `nil'.
There is no limit on the number of iterations that may occur. The
loop will continue until either CONDITION evaluates to `nil' or
until an error or `throw' jumps out of it (Note:Nonlocal Exits).
The value of a `while' form is always `nil'.
(setq num 0)
=> 0
(while (< num 4)
(princ (format "Iteration %d." num))
(setq num (1+ num)))
-| Iteration 0.
-| Iteration 1.
-| Iteration 2.
-| Iteration 3.
=> nil
To write a "repeat...until" loop, which will execute something on
each iteration and then do the end-test, put the body followed by
the end-test in a `progn' as the first argument of `while', as
shown here:
(while (progn
(forward-line 1)
(not (looking-at "^$"))))
This moves forward one line and continues moving by lines until it
reaches an empty line. It is peculiar in that the `while' has no
body, just the end test (which also does the real work of moving
point).
The `dolist' and `dotimes' macros provide convenient ways to write
two common kinds of loops.
- Macro: dolist (var list [result]) body...
This construct executes BODY once for each element of LIST, using
the variable VAR to hold the current element. Then it returns the
value of evaluating RESULT, or `nil' if RESULT is omitted. For
example, here is how you could use `dolist' to define the
`reverse' function:
(defun reverse (list)
(let (value)
(dolist (elt list value)
(setq value (cons elt value)))))
- Macro: dotimes (var count [result]) body...
This construct executes BODY once for each integer from 0
(inclusive) to COUNT (exclusive), using the variable VAR to hold
the integer for the current iteration. Then it returns the value
of evaluating RESULT, or `nil' if RESULT is omitted. Here is an
example of using `dotimes' do something 100 times:
(dotimes (i 100)
(insert "I will not obey absurd orders\n"))