This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: CS 61A Week 4 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 ;; Constructor and selector for segments ;; Note that we don't have to know what's inside a "point" for these ;; to work! (define (makesegment point1 point2) (cons point1 point2)) (define (startsegment seg) (car seg)) (define (endsegment seg) (cdr seg)) ;; Constructor and selector for points (define (makepoint xcor ycor) (cons xcor ycor)) (define (xpoint point) (car point)) (define (ypoint point) (cdr point)) ;; midpoint of segment from P1(x1,y1) to P2(x2,y2) is ;; ( (x1+x2)/2 , (y1+y2)/2 ) (define (midpointsegment seg) (makepoint (/ (+ (xpoint (startsegment seg)) (xpoint (endsegment seg))) 2) (/ (+ (ypoint (startsegment seg)) (ypoint (endsegment seg))) 2))) ;; Alternate definition, maybe fewer keystrokes, ;; maybe even easier to read: (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))))...
View
Full
Document
This note was uploaded on 05/12/2010 for the course CS 61A taught by Professor Harvey during the Spring '08 term at University of California, Berkeley.
 Spring '08
 Harvey

Click to edit the document details