# Adding, subtracting, and multiplying a vector by a scalar

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 selectors xcor-vect and ycor-vect. In terms of your selectors and constructor, implement procedures add-vect, sub-vect, and scale-vect that perform the operations vector addition, vector subtraction, and multiplying a vector by a scalar:

$$(r_1, y_1) + (r_2, y_2) = (r_1 + r_2, y_1 + y_2) \\ (r_1, y_1) - (r_2, y_2) = (r_1 - r_2, y_1 - y_2) \\ s \cdot (r, y) = (sr, sy)$$

I wrote the following:

(define (make-vect xcor ycor) (cons xcor ycor))
(define xcor-vect car)
(define ycor-vect cdr)

(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 v1 s) (make-vect (* (xcor-vect v1) s)
(* (ycor-vect v1) s)))


Can it be improved?

## 1 Answer

No.

If this would be production code, you would be better off by

  (define (sub-vect v1 v2) (add-vect v1 (scale-vect v2 -1)))


However, this is not what the exercise asks for, as everything should be written "in terms of constructors and selectors".