乐正

Actions speak louder than words.

Sicp-ex2-3

问题

请实现一种平面矩阵的表示(提示:你有可能借用练习2.2的结果)。基于你的构造函数和 选择函数定义几个过程,计算给定矩阵的周长和面积等。现在请再为矩阵实现另一种表示方 式。你应该怎样设计系统,使之能提供适当的抽象屏障,使同一个周长或者面积过程对两种 不同表示都能工作?

解答

可以使用一个点,以及宽和高的边长来确定一个长方形:

练习2.3 (ex2-3.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(define (make-rect p w h)
  (cons p
        (cons w h)))

(define (width rect)
  (car (cdr rect)))

(define (height rect)
  (cdr (cdr rect)))

(define (perimeter rect)
  (* (+ (width rect)
        (height rect))
     2))

(define (area rect)
  (* (width rect)
     (height rect)))

另一种,使用宽和高的线段定义一个长方形:

练习2.3 (ex2-3-b.scm) download
1
2
3
4
5
6
7
8
9
10
(define (other-make-rect w-segment h-segment)
  (cons w-segment h-segment))

(define (width rect)
  (abs (- (x-point (start-segment (car rect)))
          (x-point (end-segment (car rect))))))

(define (height rect)
  (abs (- (y-point (start-segment (cdr rect)))
          (y-point (end-segment (cdr rect))))))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(define rect (make-rect (make-point 3 4)
                        4
                        5))
;Value: rect

(perimeter rect)
;Value: 18

(area rect)
;Value: 20

;;; Other make-rect
(define rect (other-make-rect (make-segment 3 4 6 4)
                              (make-segment 3 4 3 9)))
;Value: rect

(area rect)
;Value: 15

(perimeter rect)
;Value: 16

draft

« sicp-ex2-2 sicp-ex2-4 »

Comments