First, what happens if the value of the argument is 1?
The function has an
if expression after the documentation
string. It tests whether the value of
number is equal to 1; if
so, Emacs evaluates the then-part of the
if expression, which
returns the number 1 as the value of the function. (A triangle with
one row has one pebble in it.)
Suppose, however, that the value of the argument is 2. In this case,
Emacs evaluates the else-part of the
The else-part consists of an addition, the recursive call to
triangle-recursively and a decrementing action; and it looks like
(+ number (triangle-recursively (1- number)))
When Emacs evaluates this expression, the innermost expression is evaluated first; then the other parts in sequence. Here are the steps in detail:
(1- number)so Emacs decrements the value of
numberfrom 2 to 1.
triangle-recursively. It does not matter that this function is contained within itself. Emacs passes the result Step 1 as the argument used by this instance of the
In this case, Emacs evaluates
triangle-recursively with an
argument of 1. This means that this evaluation of
triangle-recursively returns 1.
numberis the second element of the list that starts with
+; its value is 2.
+expression receives two arguments, the first from the evaluation of
number(Step 3) and the second from the evaluation of
The result of the addition is the sum of 2 plus 1, and the number 3 is returned, which is correct. A triangle with two rows has three pebbles in it.