Index: define-struct, Design recipe, An example using points, HTML
How would you represent a point (in two-dimensional space)? High-school algebra and geometry tells us that a point consists of an x-coordinate and a y-coordinate, where each coordinate is a number. So, we would like to create a piece of data which is a pair of numbers.
This is an example of compound data -- data which has subparts to it. Here, a point consists of two numbers. At a minimum, we need to be able to create a point and to get the coordinates in a point.
In Scheme, we can define compound data with define-struct, e.g.,
(define-struct point2 (x y))This defines a bunch of functions for manipulating point2s:
One constructor make-point2 that can be used like
(define origin (make-point2 0 0)) (define apoint2 (make-point2 5 7))
A constructor constructs one of the indicated compound things, here a point2, when given as many arguments as needed, here two.
Two selectors point2-x and point2-y that can be used like
(point2-x apoint2) (point2-y origin)
A selector selects the relevant piece of information from the compound thing, e.g., the "x" component of a point2.
One predicate point2? that can be used like
(point2? origin) (point2? 3) (point2? (make-point2 3 8))
A predicate determines whether or not its one argument is of the right form, here a point2.
Q: What would be different if we had instead used the following?
(define-struct point2 (y x))
Q: How would you define a point in three-dimensional space?
When we use compound, or structured, data, we can use a more detailed design recipe, because we know our programs should take advantage of the structure of the data.
E.g., a point2 is a (make-point2 x y), where x and y are numbers.
Q: What would they be for a function that calculates the distance of a point from the origin?
Given the kind of data that this function takes as input, what do we know? We can use its selectors! Modify the header to record this information.
; distance-from-origin : point2 -> number (define (distance-from-origin apoint2) ...(point2-x apoint2)...(point2-y apoint2)...)
Note: The template serves as a reminder to us of what the function probably looks like. We aren't obligated to use all or any of the selectors.
Define a structure of vectors (in two-dimensional space):
(define-struct vec2 ...)
Q: A vector is also a pair of numbers, so why would we define point2s and vec2s separately?
Develop a program that adds a point and a vector, returning a new point. Be sure to follow the design recipe.