[previous] [up] [next]     [index]
Next: Finger Exercises on Composing Up: Programs are Function Plus Previous: Composing Functions

Variable Definitions

external

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 tex2html_wrap_inline71582 . 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 tex2html_wrap_inline71582 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 tex2html_wrap_inline71582 , we would have to find and all instances of 3.14 in the program and replace them with 3.14159.

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.
external


Exercises

Exercise 3.2.1

Provide variable definitions for all constants that appear in the profit program of figure [cross-reference] and replace the constants with their names. Solution




PLT