www.delorie.com/gnu/docs/emacs-lisp-intro/emacs-lisp-intro_165.html | search |
Buy the book! | |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
We start with three variables: the total number of rows in the
triangle; the number of pebbles in a row; and the total number of
pebbles, which is what we want to calculate. These variables can be
named number-of-rows
, number-of-pebbles-in-row
, and
total
, respectively.
Both total
and number-of-pebbles-in-row
are used only
inside the function and are declared with let
. The initial
value of total
should, of course, be zero. However, the
initial value of number-of-pebbles-in-row
should be equal to
the number of rows in the triangle, since the addition will start with
the longest row.
This means that the beginning of the let
expression will look
like this:
(let ((total 0) (number-of-pebbles-in-row number-of-rows)) body...) |
The total number of pebbles can be found by repeatedly adding the number of pebbles in a row to the total already found, that is, by repeatedly evaluating the following expression:
(setq total (+ total number-of-pebbles-in-row)) |
After the number-of-pebbles-in-row
is added to the total
,
the number-of-pebbles-in-row
should be decremented by one, since
the next time the loop repeats, the preceding row will be
added to the total.
The number of pebbles in a preceding row is one less than the number of
pebbles in a row, so the built-in Emacs Lisp function 1-
can be
used to compute the number of pebbles in the preceding row. This can be
done with the following expression:
(setq number-of-pebbles-in-row (1- number-of-pebbles-in-row)) |
Finally, we know that the while
loop should stop making repeated
additions when there are no pebbles in a row. So the test for
the while
loop is simply:
(while (> number-of-pebbles-in-row 0) |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
webmaster | delorie software privacy |
Copyright © 2003 by The Free Software Foundation | Updated Jun 2003 |