When a number occurs many times in our program(s), we should give it a name
using a VARIABLE DEFINITION, which associates a name with a
value. One example is 3.14, which we have used in place of
. Here is how we could give this number a name:
(define PI 3.14)Now, every time we refer to PI, DrScheme replaces it with 3.14.
Using a name for a constant makes it easier to replace it with a different
value. Suppose our program contains the definition for PI, and we
decide that we need a better approximation of
for the entire
program. By changing the definition to
(define PI 3.14159)the improvement is used everywhere where we use PI. If we didn't have a name like PI for
Let us formulate this observation as our second guideline:
| Guideline on Variable Definitions Give names to frequently used constants and use the names instead of the constants in programs. |
Initially, we won't use many variable definitions for
constants, because our programs are small. But, as we learn to write
larger programs, we will make more use of variable definitions. As we will
see, the ability to have a single point of control for changes is
important for variable and function definitions.
Exercise 3.2.1
Provide variable definitions for all constants that appear in the profit
program of figure
and replace the constants with their
names. Solution