fac

fac

Robbert Haarman

2010-12-11


Introduction

This program defines a function to compute factorials, and uses it to compute the factorial of a number supplied by the user. In addition to defining functions, it demonstrates the use of if.


Discussion

Defining Functions

Just like variables, functions are defined using define. The syntax is slightly different; where for a variable you would write (define name value), for a function you write (define (name arguments) body). Here, name is the name your function, arguments names the arguments your function takes, and body specifies the code to be executed when the function is called. A function returns the value of the last expression it evaluated.

The function defined here takes one argument, n, and computes its factorial (assuming n is a number) by recursively invoking itself. Recursion is a very powerful programming construct, and often allows simple and elegant code to carry out arbitrarily large and complex tasks. Although this function does not make use of it, Scheme can optimize a specific form of recursion known as tail recursion, which can make recursive algorithms fast and memory-efficient. Tail recursion will be covered later on.

if

Often, your program needs to do different things depending on certain conditions. For this purpose, flow control constructs are provided. The simplest flow control construct is if. It takes 2 or 3 arguments: a test, an expression to be evaluated if the test returns true, and, optionally, an expression to be evaluated if the test returns false. It returns the result of the expression it evaluates (if the test returns false, but no expression is given for that case, the return value is unspecified).

In case of fac, we use if to test the value of the argument. If it is 1 or less, we return 1. If not, we return the result of multiplying n with the factorial of (- n 1), that is, n minus 1. Since we have specified values to be returned both cases, fac always returns a meaningful value, provided that the algorithm terminates. That this is indeed the case is easily verified.

Valid XHTML 1.1! Valid CSS! Viewable with Any Browser