[previous] [up] [next]     [index]
Next: Structure Definitions Up: Intermezzo 1 Syntax and Semantics Previous: Boolean Expressions

Variable Definitions

Programs consist not only of function definitions but also variable definitions, but these weren't included in our first grammar.

Here is the grammar rule for variable definitions:

tabular8222

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.


(define RADIUS 10)

(define DIAMETER (* 2 RADIUS))

;; area : number -> number ;; to compute the area of a disk with radius r (define (area r) (* 3.14 (* r r)))

(define AREA-OF-RADIUS (area RADIUS))

Figure: An example of variable definitions

Consider the sequence of definitions in figure [cross-reference]. 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.


Exercises

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)

(define DIAMETER (* 2 RADIUS))

(define CIRCUMFERENCE (* 3.14 DIAMETER))

by hand. Solution

Exercise 8.6.3

Evaluate the following sequence of definitions

(define PRICE 5)

(define SALES-TAX (* .08 PRICE))

(define TOTAL (+ PRICE SALES-TAX))

by hand. Solution


[previous] [up] [next]     [index]
Next: Structure Definitions Up: Intermezzo 1 Syntax and Semantics Previous: Boolean Expressions

PLT