Section 40

# How to Design Programs: An Introduction to Programming and Computing

• Test Prep
• davidvictor
• 20

This preview shows pages 1–3. Sign up to view the full content.

How to Design Programs: An Introduction to Computing and Programming [Go to first , previous , next page; contents ; index ] Section 40 Mutable Structures Encapsulating and managing state variables is similar to forming and managing structures. When we first apply a function that abstracts over state variables we provide initial values for some of the variables. The service manager serves the (current) value of these variables, which is similar to extracting the values of fields in structures. Not surprisingly then, the technique can simulate the constructors and selectors of a define- struct definition. This simulation naturally suggests the introduction of functions that modify the value in a structure's field. The following subsections spell out the details behind this idea; the last subsection generalizes it to vectors. 40.1 Structures from Functions (define-struct posn (x y)) (define (f-make-posn x0 y0) (local ((define x y0) (define y y0) (define (service-manager msg) (cond [(symbol=? msg 'x) x] [(symbol=? msg 'y) y] [else (error 'posn "...")]))) service-manager)) (define (f-posn-x p) (p 'x)) (define (f-posn-y p) (p 'y)) Figure 116: A functional analog of posn Take a look at figure 116 . The left-hand side is the one-line definition of a posn structure. The right-hand side is a functional definition that provides almost all the same services. In particular, the definition provides a constructor that consumes two values and constructs a compound value, and two selectors for extracting the values that went into the construction of a compound value. (1 of 20) [2/5/2008 4:58:51 PM]

This preview has intentionally blurred sections. Sign up to view the full version.