How to Design Programs: An Introduction to Computing and Programming
Programs are Function Plus Variable Definitions
In general, a program consists not just of one, but of many definitions. The
program, for example, consists
of two definitions: the one for
and another one for
. We refer to both as
FUNCTION DEFINITIONs and, using mathematical terminology in a loose way, say that the program is COMPOSED of
several functions. Because the first one,
, is the function we really wish to use, we refer to it as the
MAIN FUNCTION; the second one,
, is an AUXILIARY FUNCTION, occasionally also called HELPER FUNCTION.
The use of auxiliary functions makes the design process manageable and renders programs readable. Compare the
following two versions of
(define (area-of-ring outer
(- (area-of-disk outer)
(define (area-of-ring outer
(- (* 3.14 (* outer outer))
(* 3.14 (* inner inner))))
The definition on the left composes auxiliary functions. Designing it helped us break up the original problem into smaller,
more easily solvable problems. Reading it reminds us of our reasoning that the area is the difference between the area of
the full disk and the area of the hole. In contrast, the definition on the right requires a reader to reconstruct the idea that the
two subexpressions compute the area of two disks. Furthermore, we would have had to produce the right definition in
one monolithic block, without benefit of dividing the problem-solving process into smaller steps.
For a small program such as
, the differences between the two styles are minor. For large programs,
however, using auxiliary functions is not an option but a necessity. That is, even if we are asked to write a single program,
we should consider breaking it up into several small programs and COMPOSING them as needed. Although we are not yet in
a position to develop truly large programs, we can still get a feeling for the idea by developing two versions in parallel.
The first subsection contrasts the two development styles with an example from the business domain. It demonstrates
how breaking up a program into several function definitions can greatly increase our confidence in the correctness of
the overall program. The second subsection introduces the concept of a variable definition, which is an additional
important ingredient for the development of programs. The last subsection proposes some exercises.
Consider the following problem:
Imagine the owner of a movie theater who has complete freedom in setting ticket prices. The more he charges, the
fewer the people who can afford tickets. In a recent experiment the owner determined a precise relationship between
the price of a ticket and average attendance. At a price of $5.00 per ticket, 120 people attend a performance.
Decreasing the price by a dime ($.10) increases attendance by 15. Unfortunately, the increased attendance also