Node:Recursive Example arg of 1 or 2, Next:Recursive Example arg of 3 or 4, Previous:Recursive triangle function, Up:Recursive triangle function
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 if expression.
The else-part consists of an addition, the recursive call to
triangle-recursively and a decrementing action; and it looks like
this:
(+ 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 number from 2 to 1.
triangle-recursively function.
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 triangle-recursively
function
In this case, Emacs evaluates triangle-recursively with an
argument of 1. This means that this evaluation of
triangle-recursively returns 1.
number.
number is the second element of the list that
starts with +; its value is 2.
+ expression.
+ expression receives two arguments, the first
from the evaluation of number (Step 3) and the second from the
evaluation of triangle-recursively (Step 2).
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.