2
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 15, 2011 at 3:01
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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".

answered Apr 15, 2011 at 4:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.