next up previous
Contents Next: When To Use Up: Recursion and Iteration Previous: Local Variables Using

Iteration Using Dolist

Dolist is very much like dotimes, except that the iteration is controlled by the length of a list, rather than by the value of a count. Here is the general form for dolist:

  (dolist (<next-element>  <target-list>  <result> ) <body> )
In a dolist statment result and body work just as in dotimes. Next-element is the name of a variable which is intially set to the first element of target-list (which must therefore be a list). The next time through, next-element is set to the second element of target-list and so on until the end of target-list is reached, at which point result-form is evaluated and returned.

Here is num-sublists done as an example:

     (defun num-sublists-i (lis)
        (let ((result 0))
           (dolist (next lis result)
              (if (listp next) 
                  (setf result (1+ result))))))
The function num-sublists-i works because result is incremented only whenever the current element of the list indicated by next is itself a list. Notice that in the case where the next element of the list is not itself a list there is no need to do anything. Thus, in the if statement of the definition it is possible to omit the else clause entirely.

© Colin Allen & Maneesh Dhagat
March 2007