GNU Info

Info Node: (emacs-lisp-intro.info)Recursive triangle function

(emacs-lisp-intro.info)Recursive triangle function


Next: Recursion with cond Prev: Recursion with list Up: Recursion
Enter node , (file) or (file)node

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.

Recursive Example arg of 1 or 2
Recursive Example arg of 3 or 4

automatically generated by info2www version 1.2.2.9