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. Since the echo
area is only one line, we cannot illustrate how it works in the same
way we have been illustrating functions in the past, by evaluating
them inside Info. Instead, you need to copy the necessary
expressions to your `*scratch*' buffer and evaluate them there.
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
(copy-region-as-kill
). 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: ^Jgiraffe^J^Jgazelle^J^Jlion^J^Jtiger^Jnil
, in which
each `^J' stands for the newline that in the `*scratch*'
buffer puts each word on its own line. You can evaluate these
expressions right now in the Info buffer, if you like, to see this
effect.)
(setq animals '(giraffe gazelle 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 in the `*scratch*' buffer, this will be printed in the buffer:
giraffe gazelle lion tiger nil
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.
Go to the first, previous, next, last section, table of contents.