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) (make-rational (+ (* (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 (make-segment point1 point2) (cons point1 point2)) (define (start-segment seg) (car seg)) (define (end-segment seg) (cdr seg)) ;; Constructor and selector for points (define (make-point xcor ycor) (cons xcor ycor)) (define (x-point point) (car point)) (define (y-point point) (cdr point)) ;; midpoint of segment from P1(x1,y1) to P2(x2,y2) is ;; ( (x1+x2)/2 , (y1+y2)/2 ) (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))) ;; Alternate definition, maybe fewer keystrokes, ;; maybe even easier to read: (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))))...
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