Comp 210 Lab 2: Data Structures

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:

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?

Design Recipe for Compound Data

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.

  1. Formulate a data definition.

    E.g., a point2 is a (make-point2 x y), where x and y are numbers.

  2. Write the function's contract, purpose, and header.

    Q: What would they be for a function that calculates the distance of a point from the origin?

  3. Make some examples of what the function should do.
  4. Make a template for the function body.

    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.

  5. Write the function body.
  6. Test the function.

An example with points

To do:

  1. 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?

  2. Develop a program that adds a point and a vector, returning a new point. Be sure to follow the design recipe.