Do ex 2.2 and 2.3

This commit is contained in:
Felix Martin 2020-10-24 11:24:13 -04:00
parent 1a8a806f35
commit 69e6d171d4
2 changed files with 60 additions and 0 deletions

View File

@ -53,3 +53,61 @@
(display "\n\nex-2.2")
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (make-segment a b) (cons a b))
(define (start-segment s) (car s))
(define (end-segment s) (cdr s))
(define (midpoint-segment s)
(make-point (average (x-point (start-segment s)) (x-point (end-segment s)))
(average (y-point (start-segment s)) (y-point (end-segment s)))))
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ", ")
(display (y-point p))
(display ")"))
(define s (make-segment (make-point 1 2) (make-point 7 4)))
(print-point (midpoint-segment s))
(display "\n\nex-2.3\n")
; The first representation takes the two opposite corners of the rectangle.
(define (make-rectangle p1 p2) (cons p1 p2))
(define (corner-1-rectangle r) (car r))
(define (corner-2-rectangle r) (cdr r))
(define (area-rectangle r)
(abs (* (- (x-point (corner-1-rectangle r)) (x-point (corner-2-rectangle r)))
(- (y-point (corner-1-rectangle r)) (y-point (corner-2-rectangle r))))))
(define (perimeter-rectangle r)
(* 2 (+ (abs (- (x-point (corner-1-rectangle r)) (x-point (corner-2-rectangle r))))
(abs (- (y-point (corner-1-rectangle r)) (y-point (corner-2-rectangle r)))))))
(define r (make-rectangle (make-point -2 -2) (make-point -8 -10)))
(display (area-rectangle r)) (newline)
(display (perimeter-rectangle r)) (newline)
; The second representation takes one corner and the size of the rectangle.
; The consequence is that we have to calculate the second point for the
; corner-2 getter.
(define (make-rectangle p1 size) (cons p1 size))
(define (corner-1-rectangle r) (car r))
(define (corner-2-rectangle r)
(make-point (+ (x-point (car r)) (x-point (cdr r)))
(+ (y-point (car r)) (y-point (cdr r)))))
; Our higher level functions still deliver the same result even though the
; underlying presentation of the rectangle is different.
(define r (make-rectangle (make-point -2 -2) (make-point -6 -8)))
(display (area-rectangle r)) (newline)
(display (perimeter-rectangle r)) (newline)
(display "\nex-2.4\n")

View File

@ -10,4 +10,6 @@
(define (gcd a b)
(if (= b 0) (abs a) (gcd b (remainder a b))))
(define (average a b) (/ (+ a b) 2.0))
;(assert (gcd 93 15) 3)