Go to the previous, next section.

Recursion with a List

The example of a  while loop that printed the elements of a list of numbers can be written recursively. Here is the code, including an expression to set the value of the variable  animals to a list.

This example must be copied to the `*scratch*' buffer and each expression must be evaluated there. Use C-u C-x C-e to evaluate the  (print-elements-recursively animals) expression so that the results are printed in the buffer; otherwise the Lisp interpreter will try to squeeze the results into the one line of the echo area.

Also, place your cursor immediately after the last closing parenthesis of the  print-elements-recursively function, before the comment. Otherwise, the Lisp interpreter will try to evaluate the comment.

(setq animals '(giraffe gazelle lion tiger))

(defun print-elements-recursively (list)
  "Print each element of LIST on a line of its own.
Uses recursion."
  (print (car list))                  ; body
  (if list                            ; do-again-test
      (print-elements-recursively     ; recursive call
       (cdr list))))                  ; next-step-expression

(print-elements-recursively animals)

The  print-elements-recursively function first prints the first element of the list, the CAR of the list. Then, if the list is not empty, the function invokes itself, but gives itself as its argument, not the whole list, but the second and subsequent elements of the list, the CDR of the list.

When this evaluation occurs, the function prints the first element of the list it receives as its argument (which is the second element of the original list). Then, the  if expression is evaluated and when true, the function calls itself with the CDR of the list it is invoked with, which (the second time around) is the CDR of the CDR of the original list.

Each time the function invokes itself, it invokes itself on a shorter version of the original list. Eventually, the function invokes itself on an empty list. The  print function prints the empty list as  nil . Next, the conditional expression tests the value of  list . Since the value of  list is  nil , the  if expression tests false so the then-part is not evaluated. The function as a whole then returns  nil . Consequently, you see  nil twice when you evaluate the function.

When you evaluate  (print-elements-recursively animals) in the `*scratch*' buffer, you see this result:







(The first  nil is the value of the empty list that is printed; the second  nil is the value returned by the whole function.)

Go to the previous, next section.