[previous] [up] [next]     [index]
Next: Functions that Change Memory Up: Designing Functions with Memory Previous: Memory and State Variables

Functions that Initialize Memory

After we have developed contracts and purpose statements for the state variables of a program, we immediately define a function that sets the state variables to proper values. We call this function an INITIALIZATION FUNCTION or an INITIALIZER. A program's initializer is the first function that is used during an execution; a program may also provide other means to invoke the initializer.

For our current examples, the initializers are straightforward. Here is one for the address-book example:

;; init-address-book : -> void 
(define (init-address-book) 
  (set! address-book empty)) 
The one for traffic-light is equally trivial:
;; init-traffic-light : -> void 
(define (init-traffic-light) 
  (set! current-color 'red)) 
In setting current-color to 'red, we follow a conventional rule of engineering to put devices into their least harmful state when starting it up.[footnote]

At first glance, these initializers don't seem to add much to our programs. Both set the respective state variables to the values that are their defined values. For both cases, however, it is easy to see that the initializer could do some additional useful work. The first one, for example, could create and display the graphical user interface for an address book; the second one could create and display a canvas that displays the current state of the traffic light.



PLT