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


An argument of 3

Suppose that triangle-recursively is called with an argument of 3.

Step 1 Evaluate the do-again-test.
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.)
Step 2 Evaluate the innermost expression of the else-part.
The innermost expression of the else-part is evaluated, which decrements 3 to 2. This is the next-step-expression.
Step 3 Evaluate the 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.
Step 4 Evaluate the addition.
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 with a smaller argument, until the argument is small enough so that it does not evaluate itself.


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