# lab5 - CS 61A Week 5 solutions LAB EXERCISES Skipping the...

This preview shows pages 1–3. Sign up to view the full content.

Sheet1 Page 1 CS 61AWeek 5 solutions LAB EXERCISES: Skipping the ones that just say "try this". .. 5 (define (+rat a b) (make-rational (+ (* (numerator a) (denominator b)) (* (denominator a) (numerator b))) (* (denominator a) (denominator b)))) 2.2 (define (make-segment point1 point2) (cons point1 point2)) (define (start-segment seg) (car seg)) (define (end-segment seg) (cdr seg)) (define (make-point xcor ycor) (cons xcor ycor)) (define (x-point point) (car point)) (define (y-point point) (cdr point)) (define (midpoint-segment seg) (make-point (/ (+ (x-point (start-segment seg)) (x-point (end-segment seg))) 2) (/ (+ (y-point (start-segment seg)) (y-point (end-segment seg))) 2)))

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Sheet1 Page 2 (define (midpoint-segment seg) (let ((p1 (start-segment seg)) (p2 (end-segment seg))) (make-point (/ (+ (x-point p1) (x-point p2)) 2) (/ (+ (y-point p1) (y-point p2)) 2))) Note: If you wanted to write (define (make-segment 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 (make-rectangle side1 side2) (cons side1 side2)) (define (first-leg rect) (car rect)) (define (second-leg rect) (cdr rect)) Perimeter and area: (define (perimeter rect) (* 2 (+ (length-segment (first-leg rect)) (length-segment (second-leg rect))))) (define (area rect) (* (length-segment (first-leg rect)) (length-segment (second-leg rect)))) (define (length-segment seg) (sqrt (+ (square (- (x-point (end-segment seg)) (x-point (start-segment seg)))) (square (- (y-point (end-segment seg)) (y-point (start-segment 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.

### Page1 / 12

lab5 - CS 61A Week 5 solutions LAB EXERCISES Skipping the...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online