Exercise 2.1
#lang racket
;the greatest common divisor of the two integers
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
;reduce the numerator and the denominator to the lowest terms
(define (make-rat-lowest a b)
(let ((g (abs (gcd a b))))
(cons (/ a g) (/ b g))))
;get the answer satisfied the require
(define (make-rat n d)
(cond ((and (< n 0) (< d 0))
(make-rat-lowest (- n) (- d)))
((and (< d 0) (> n 0))
(make-rat-lowest (- n) (- d)))
(else
(make-rat-lowest n d))))
Exercise 2.2
#lang racket
;segment constructor and selectors
(define (make-segment start end)
(cons start end))
(define (start-segment segment)
(car segment))
(define (end-segment segment)
(cdr segment))
;point constructor and selectors
(define make-point cons)
(define x-point car)
(define y-point cdr)
;middle-point of the designate segment
(define (average x y)
(/ (+ x y) 2))
(define (midpoint-segment segment)
(make-point
(average (x-point (start-segment segment)) (x-point (end-segment segment)))
(average (y-point (start-segment segment)) (y-point (end-segment segment)))))
;output to the console
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")"))
(print-point (midpoint-segment (make-segment (make-point 1.0 2.0) (make-point 2.0 2.0))))
Exercise 2.3
#lang racket
;compute the perimeter and area of the rectangle
;no matter how rect-width and rect-height implemented
(define (rect-perimeter rect)
(+ (* 2 (rect-width rect))
(* 2 (rect-height rect))))
(define (rect-area rect)
(* (rect-width rect)
(rect-height rect)))
;rectangle constructor and selectors
(define (make-rect p1 p2)
(make-segment p1 p2))
(define (rect-width rect)
(abs (- (x-point (start-segment rect))
(x-point (end-segment rect)))))
(define (rect-height rect)
(abs (- (y-point (start-segment rect))
(y-point (end-segment rect)))))
Summarize
- wishful thinking是一种很好的编写抽象程序的指导方法,可以使我们编写“期望”的方法,而忽略底层实现。
- 数据抽象提供了一种 abstraction barriers,通过提供constructor和selector接口,使我们可以直接访问数据结构而忽略其底层实现,也就是说,底层实现可以任意的组织。