sicp 2.46

Exercise 2.46.  A two-dimensional vector v running from the origin to a point can be represented as a pair consisting of an x-coordinate and a y-coordinate. Implement a data abstraction for vectors by giving a constructor make-vect and corresponding selectorsxcor-vect and ycor-vect. In terms of your selectors and constructor, implement procedures add-vectsub-vect, and scale-vect that perform the operations vector addition, vector subtraction, and multiplying a vector by a scalar:

 



(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)
  (cons (+ (xcor-vect v1) (xcor-vect v2))
        (+ (ycor-vect v1) (ycor-vect v2))))

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

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

你可能感兴趣的:(SICP)