11.3.4 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.) The function evaluates to 28.

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.