Index: define-struct, Design recipe, Ping-pong example
First, congratulations you have graduated to DrScheme's "intermediate" language level! What we will be introducing isn't allowed in the beginner level. In DrScheme, select Configure Language Level from the Language Level menu. Choose Intermediate from the resulting menu. Click Execute.
In class we made a data definition for a point (point = a list of two numbers). We then defined several helper functions so that we could just think in terms of points rather than lists of two numbers:
(define (make-point x y) (cons x (cons y empty))) (define (point-x point) (first point)) (define (point-y point) (first (rest point)))
Doing this sort of thing is very common and also very straightforward. In fact, it's a good thing to automate, so we do. Instead of the above, we can use
(define-struct point (x y))This defines functions like the above, and more. In fact, it defines
One constructor make-point.
A constructor constructs one of the indicated compound things, here a point, when given as many arguments as needed, here two.
Two selectors point-x and point-y.
A selector selects the relevant piece of information from the compound thing, e.g., the "x" component of a point.
One predicate point?.
A predicate answers the question whether or not its one argument is of the right form, here a point.
Q: What do each of the following return?
(make-point 3 4) (point? (make-point 3 4)) (point? (cons 3 (cons 4 empty)))
We originally represented a point as a two-element list. Well, that seems kind of strange:
Q: Would it matter if we had typed (define-struct point (y x)), instead?
Let's remind ourselves of what the Design Recipe is. We'll need a couple new steps when dealing with structured, or compound, data like the above.
As above, for a point.
I.e., given the kind of data that this function takes as input, what do we know? We can use its selectors!
; distance-to-point : point -> number (define (distance-to-point point) ...(point-x point)...(point-y point)...)
To do: Let's play ping-pong. In DrScheme, load the library teach/pingp-play-lib.ss. (In the Language menu, use Set Library To...") Now start the game with (go 'John) (use your name, although it doesn't matter), and click in the window it creates. Click near the paddles to move them.
Ok, now we are going to start writing this program. Don't be afraid -- we're going to go step-by-step, and give you lots of code to do all the drawing stuff. To load some support code into DrScheme, load the library pingp-lib.ss.
To do: Form pairs of students. Do the exercises in section 5.4. You won't finish all these exercises during lab, but hopefully you'll be interested enough to finish on your own. Warning: The online version is garbled in places, so here's an outline: