next up previous
Contents Next: Iteration Using Dotimes Up: Recursive Definitions Previous: Using Trace To

Another Example

Here's another recursive function. This one counts the number of elements of a list that are themselves lists:

(defun num-sublists (lis)
    ((null lis) 0)                   ;; stop if no elements
    ((listp (first lis))             ;; first is a list
     (1+ (num-sublists (rest lis)))) ;; add to number in rest
    (t (num-sublists (rest lis)))))  ;; else count in rest

Try this function out on various examples (and don't forget to use trace to see what it is doing). Also, think about what would happen if num-sublists is called with an atom as its argument, and how you might alter the definition to handle this.

© Colin Allen & Maneesh Dhagat
March 2007