Understanding Code

 

Slide 20

next »

Another investigation, this one focusing on function calls and expanding a computation. Here is a piece of Lisp code that we wish to understand. It calculates the factorial of a number. 5 factorial, for example, is 5 * 4 * 3 * 2 * 1, or 120. Note that 5 factorial is 5 times 4 factorial. The code uses this fact to calculate factorial. If the number is less than 1, its factorial is 1. Otherwise its factorial is the number times the factorial of one less than the number. At the bottom, the factorial function has been called on the number 3, and the result 6 has been returned.