Go to the first, previous, next, last section, table of contents.


Recursion in Place of a Counter

The triangle function described in a previous section can also be written recursively. It looks like this:

(defun triangle-recursively (number)
  "Return the sum of the numbers 1 through NUMBER inclusive.
Uses recursion."
  (if (= number 1)                    ; do-again-test
      1                               ; then-part
    (+ number                         ; else-part
       (triangle-recursively          ; recursive call
        (1- number)))))               ; next-step-expression

(triangle-recursively 7)

You can install this function by evaluating it and then try it by evaluating (triangle-recursively 7). (Remember to put your cursor immediately after the last parenthesis of the function definition, before the comment.)

To understand how this function works, let's consider what happens in the various cases when the function is passed 1, 2, 3, or 4 as the value of its argument.

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:

Step 1 Evaluate the innermost expression.
The innermost expression is (1- number) so Emacs decrements the value of number from 2 to 1.
Step 2 Evaluate the triangle-recursively function.
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.
Step 3 Evaluate the value of number.
The variable number is the second element of the list that starts with +; its value is 2.
Step 4 Evaluate the + expression.
The + 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.


Go to the first, previous, next, last section, table of contents.