6.001 Structure and Interpretation of Computer Programs
Recitation #6
Wednesday, September 29, 2004
Review
- higher-order procedures, e.g., map
Practice
1. Here is an abstraction for a vector, which represents a
point (x,y) in the plane.
- (make-vect x y) constructs a vector
- (get-x v) accesses a vector's x coordinate
- (get-y v) accesses a vector's y coordinate
(a) Write down the contract for the vector abstraction.
(b) Implement the abstraction when a vector is represented by a pair.
(c) Implement the abstraction when a vector is represented by a list.
(d) Implement the abstraction when a vector is represented by a
procedure.
2. Using the vector abstraction, write the following operations on
vectors.
(a) (+vect v1 v2) adds two vectors v1 and v2
using vector addition
(b) (-vect v1 v2) subtracts v2 from v1
(c) (scale-vect v k) multiplies vector v by the
(scalar) factor k
(d) (mag v) computes the
length of a vector.
(e) (=vect? v1 v2) returns true if v1 is the same
point as v2
3. Define another abstraction, curve, to represent a sequence
of line segments whose start and end points are vectors.
- (make-curve v) constructs an empty curve, i.e. having no
line segments and start point v.
- (extend-curve v c) constructs a curve by inserting a new
point v at the start of another curve c.
- (start-point c) returns a curve's start point.
- (rest-of-curve c) removes a curve's first line segment
and returns the rest of it.
- (empty-curve? c) returns true if a curve has no
line segments.
(a) Write down the contract for the curve abstraction.
(b) Implement the abstraction when a curve is represented as a list of
points.
(c) Implement the abstraction when a curve is represented by a
procedure.
4. Using the curve abstraction and vector operations, define the
following operations on curves:
(a) (scale c k) scales every point in a curve by the scale
factor k.
(b) (translate c v) translates every point in a curve by
vector v.
(c) (perimeter c) computes
the sum of the lengths of the line segments in a curve.
(d) (closed? c) tests whether the curve's start point is the
same as its end point.