Sheet1
Page 1
CS 61AWeek 5 solutions
LAB EXERCISES:
Skipping the ones that just say "try this".
..
5
(define (+rat a b)
(makerational (+ (* (numerator a) (denominator b))
(* (denominator a) (numerator b)))
(* (denominator a) (denominator b))))
2.2
(define (makesegment point1 point2)
(cons point1 point2))
(define (startsegment seg)
(car seg))
(define (endsegment seg)
(cdr seg))
(define (makepoint xcor ycor)
(cons xcor ycor))
(define (xpoint point)
(car point))
(define (ypoint point)
(cdr point))
(define (midpointsegment seg)
(makepoint (/ (+ (xpoint (startsegment seg))
(xpoint (endsegment seg)))
2)
(/ (+ (ypoint (startsegment seg))
(ypoint (endsegment seg)))
2)))
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentSheet1
Page 2
(define (midpointsegment seg)
(let ((p1 (startsegment seg))
(p2 (endsegment seg)))
(makepoint (/ (+ (xpoint p1) (xpoint p2)) 2)
(/ (+ (ypoint p1) (ypoint p2)) 2)))
Note: If you wanted to write (define (makesegment x1 y1 x2 y2) .
..) or
something similar, it means you don't yet believe that abstract data
types are legitimate things, valid arguments to procedures and so on.
Just as in section 1.3 you had to learn to accept that procedures are
just as good as numbers, now you have to accept that points (or any
other abstract type) are just as good as numbers!
2.3
Since the hint suggests using exercise 2.2, let's represent a rectangle
as two adjacent sides (adjacent so that we get one length and one width).
(define (makerectangle side1 side2)
(cons side1 side2))
(define (firstleg rect)
(car rect))
(define (secondleg rect)
(cdr rect))
Perimeter and area:
(define (perimeter rect)
(* 2 (+ (lengthsegment (firstleg rect))
(lengthsegment (secondleg rect)))))
(define (area rect)
(* (lengthsegment (firstleg rect))
(lengthsegment (secondleg rect))))
(define (lengthsegment seg)
(sqrt (+ (square ( (xpoint (endsegment seg))
(xpoint (startsegment seg))))
(square ( (ypoint (endsegment seg))
(ypoint (startsegment seg)))))))
Different representation for rectangles:
Note that the representation
above really contains more information than necessary
common point twice, and it doesn't take into account that the angle
between the two legs must be 90 degrees.
So instead we could represent
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 mckenzie

Click to edit the document details