Node:dotimes, Previous:dolist, Up:dolist dotimes
dotimes macro is similar to
dolist, except that it
loops a specific number of times.
The first argument to
dotimes is assigned the numbers 0, 1, 2
and so forth each time around the loop, and the value of the third
argument is returned. You need to provide the value of the second
argument, which is how many times the macro loops.
For example, the following binds the numbers from 0 up to, but not including, the number 3 to the first argument, number, and then constructs a list of the three numbers. (The first number is 0, the second number is 1, and the third number is 2; this makes a total of three numbers in all, starting with zero as the first number.)
(let (value) ; otherwise a value is a void variable (dotimes (number 3 value) (setq value (cons number value)))) => (2 1 0)
value, so the way to use
dotimes is to operate on some expression number number of
times and then return the result, either as a list or an atom.
Here is an example of a
defun that uses
dotimes to add
up the number of pebbles in a triangle.
(defun triangle-using-dotimes (number-of-rows) "Using dotimes, add up the number of pebbles in a triangle." (let ((total 0)) ; otherwise a total is a void variable (dotimes (number number-of-rows total) (setq total (+ total (1+ number)))))) (triangle-using-dotimes 4)