www.delorie.com/gnu/docs/emacs-lisp-intro/emacs-lisp-intro_176.html | search |
Buy the book! | |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Suppose that triangle-recursively
is called with an argument of
3.
The if
expression is evaluated first. This is the do-again
test and returns false, so the else-part of the if
expression
is evaluated. (Note that in this example, the do-again-test causes
the function to call itself when it tests false, not when it tests
true.)
The innermost expression of the else-part is evaluated, which decrements 3 to 2. This is the next-step-expression.
triangle-recursively
function.
The number 2 is passed to the triangle-recursively
function.
We know what happens when Emacs evaluates triangle-recursively
with
an argument of 2. After going through the sequence of actions described
earlier, it returns a value of 3. So that is what will happen here.
3 will be passed as an argument to the addition and will be added to the number with which the function was called, which is 3.
The value returned by the function as a whole will be 6.
Now that we know what will happen when triangle-recursively
is
called with an argument of 3, it is evident what will happen if it is
called with an argument of 4:
In the recursive call, the evaluation of
(triangle-recursively (1- 4))will return the value of evaluating
(triangle-recursively 3)which is 6 and this value will be added to 4 by the addition in the third line.
The value returned by the function as a whole will be 10.
Each time triangle-recursively
is evaluated, it evaluates a
version of itself--a different instance of itself--with a smaller
argument, until the argument is small enough so that it does not
evaluate itself.
Note that this particular design for a recursive function requires that operations be deferred.
Before (triangle-recursively 7)
can calculate its answer, it
must call (triangle-recursively 6)
; and before
(triangle-recursively 6)
can calculate its answer, it must call
(triangle-recursively 5)
; and so on. That is to say, the
calculation that (triangle-recursively 7)
makes must be
deferred until (triangle-recursively 6)
makes its calculation;
and (triangle-recursively 6)
must defer until
(triangle-recursively 5)
completes; and so on.
If each of these instances of triangle-recursively
are thought
of as different robots, the first robot must wait for the second to
complete its job, which must wait until the third completes, and so
on.
There is a way around this kind of waiting, which we will discuss in Recursion without Deferments.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
webmaster donations bookstore | delorie software privacy |
Copyright © 2003 by The Free Software Foundation | Updated Jun 2003 |