Next: , Up: Recursive triangle function   [Contents][Index]


An argument of 1 or 2

First, what happens if the value of the argument is 1?

The function has an if expression after the documentation string. It tests whether the value of number is equal to 1; if so, Emacs evaluates the then-part of the if expression, which returns the number 1 as the value of the function. (A triangle with one row has one pebble in it.)

Suppose, however, that the value of the argument is 2. In this case, Emacs evaluates the else-part of the if expression.

The else-part consists of an addition, the recursive call to triangle-recursively and a decrementing action; and it looks like this:

(+ number (triangle-recursively (1- number)))

When Emacs evaluates this expression, the innermost expression is evaluated first; then the other parts in sequence. Here are the steps in detail:

Step 1    Evaluate the innermost expression.

The innermost expression is (1- number) so Emacs decrements the value of number from 2 to 1.

Step 2    Evaluate the triangle-recursively function.

The Lisp interpreter creates an individual instance of triangle-recursively. It does not matter that this function is contained within itself. Emacs passes the result Step 1 as the argument used by this instance of the triangle-recursively function

In this case, Emacs evaluates triangle-recursively with an argument of 1. This means that this evaluation of triangle-recursively returns 1.

Step 3    Evaluate the value of number.

The variable number is the second element of the list that starts with +; its value is 2.

Step 4    Evaluate the + expression.

The + expression receives two arguments, the first from the evaluation of number (Step 3) and the second from the evaluation of triangle-recursively (Step 2).

The result of the addition is the sum of 2 plus 1, and the number 3 is returned, which is correct. A triangle with two rows has three pebbles in it.


Next: , Up: Recursive triangle function   [Contents][Index]

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