乐正

Actions speak louder than words.

Sicp-ex2-46

问题

从远点除法的一个两维向量$v$可以用一个由$x$坐标和$y$坐标构成的序对表示。请为这样 像向量实现一个数据抽象:给出一个构造函数make-vect,以及对应的选择函数xcor-vectycor-vect。借助于你给出的构造函数和选择函数,实现过程add-vectsub-vectscale-vect,他们够能完成向量加法、向量减法和向量的伸缩。

$$ \begin{align} (x_1, y_1) + (x_2, y_2) & = (x_1 + x_2, y_1 + y_2) \\ (x_1, y_1) - (x_2, y_2) & = (x_1 - x_2, y_1 - y_2) \\ s \cdot (x, y) & = (sx, sy) \end{align} $$

解答

练习2.46 (ex2-46.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(define (make-vect x y)
  (cons x y))

(define (xcor-vect vect)
  (car vect))

(define (ycor-vect vect)
  (cdr vect))

(define (add-vect v1 v2)
  (make-vect (+ (xcor-vect v1)
                (xcor-vect v2))
             (+ (ycor-vect v1)
                (ycor-vect v2))))

(define (sub-vect v1 v2)
  (make-vect (- (xcor-vect v1)
                (xcor-vect v2))
             (- (ycor-vect v1)
                (ycor-vect v2))))

(define (scale-vect s vect)
  (make-vect (* s (xcor-vect vect))
             (* s (ycor-vect vect))))

draft

« sicp-ex2-45 sicp-ex2-47 »

Comments