Here is the grammar rule for variable definitions:
The shape of a variable definition is similar to that of a function definition. It starts with a ``('', followed by the keyword define, followed by a variable, followed by an expression, and closed by a right parenthesis ``)'' that matches the very first one. The keyword define distinguishes variable definitions from expressions, but not from function definitions. For that, a reader must look at the second component of the definition.
Next we must understand what a variable definition means. A variable definition like
(define RADIUS 5)has a plain meaning. It says that wherever we encounter RADIUS during an evaluation, we may replace it with 5.
When DrScheme encounters a definition with a proper expression on the right-hand side, it must evaluate that expression immediately. For example, the right-hand side of the definition
(define DIAMETER (* 2 RADIUS))is the expression (* 2 RADIUS). Its value is 10 because RADIUS stands for 5. Hence we can act as if we had written
(define DIAMETER 10)
In short, when DrScheme encounters a variable definition, it determines the value of the right-hand side. For that step, it uses all those definitions that precede the current definition but not those that follow. Once DrScheme has a value for the right-hand side, it remembers that the name on the left-hand side stands for this value. Whenever we evaluate an expression, every occurrence of the defined variable is replaced by its value.
Consider the sequence of definitions in figure
.
As DrScheme steps through this sequence of definitions, it first determines
that RADIUS stands for 10, DIAMETER for
20, and area is the name of a function. Finally, it evaluates
(area RADIUS) to 314.0 and associates
AREA-OF-RADIUS with that value.
Exercise 8.6.1
Make up five examples of variable definitions. Use constants and expressions on the right-hand side. Solution
Exercise 8.6.2
Evaluate the following sequence of definitions
(define RADIUS 10)by hand. Solution(define DIAMETER (* 2 RADIUS))
(define CIRCUMFERENCE (* 3.14 DIAMETER))
Exercise 8.6.3
Evaluate the following sequence of definitions
(define PRICE 5)by hand. Solution(define SALES-TAX (* .08 PRICE))
(define TOTAL (+ PRICE SALES-TAX))