Next: , Previous: , Up: Recursion   [Contents][Index]


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.

This page has generated for branch:work/add_lispintr, commit:65845cf60c073f2f3182d1d07483530e9bbe1d96 to check Japanese translation.