Next: , Previous: Loop Example, Up: while

11.1.2 An Example: print-elements-of-list

The print-elements-of-list function illustrates a while loop with a list.

The function requires several lines for its output. If you are reading this in a recent instance of GNU Emacs, you can evaluate the following expression inside of Info, as usual.

If you are using an earlier version of Emacs, you need to copy the necessary expressions to your *scratch* buffer and evaluate them there. This is because the echo area had only one line in the earlier versions.

You can copy the expressions by marking the beginning of the region with C-<SPC> (set-mark-command), moving the cursor to the end of the region and then copying the region using M-w (kill-ring-save, which calls copy-region-as-kill and then provides visual feedback). In the *scratch* buffer, you can yank the expressions back by typing C-y (yank).

After you have copied the expressions to the *scratch* buffer, evaluate each expression in turn. Be sure to evaluate the last expression, (print-elements-of-list animals), by typing C-u C-x C-e, that is, by giving an argument to eval-last-sexp. This will cause the result of the evaluation to be printed in the *scratch* buffer instead of being printed in the echo area. (Otherwise you will see something like this in your echo area: ^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil, in which each ‘^J’ stands for a `newline'.)

In a recent instance of GNU Emacs, you can evaluate these expressions directly in the Info buffer, and the echo area will grow to show the results.

     (setq animals '(gazelle giraffe lion tiger))
     (defun print-elements-of-list (list)
       "Print each element of LIST on a line of its own."
       (while list
         (print (car list))
         (setq list (cdr list))))
     (print-elements-of-list animals)

When you evaluate the three expressions in sequence, you will see this:


Each element of the list is printed on a line of its own (that is what the function print does) and then the value returned by the function is printed. Since the last expression in the function is the while loop, and since while loops always return nil, a nil is printed after the last element of the list.