Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 2.46

From Drewiki
Jump to: navigation, search

Problem

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:


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

Solution

cons pairs are a good match for the two-dimensional vector representation. The constructor and selectors are trivial:

(define (make-vect x y)
  (cons x y))
 
(define (xcor-vect v)
  (car v))
 
(define (ycor-vect v)
  (cdr v))

Test:

(define v1 (make-vect 2 3))
 
(define v2 (make-vect -1 6))
 
(xcor-vect v1)

Output:

2
(ycor-vect v1)

Output:

3
(xcor-vect v2)

Output:

-1
(ycor-vect v2)

Output:

6


Implementing the vector operation procedures is also straightforward. Here is one possible set of implementations:

(define (add-vect v1 v2)
  (make-vect (+ (xcor-vect v1)
                (xcor-vect v2))
             (+ (ycor-vect v1)
                (ycor-vect v2))))
 
(define (scale-vect s v)
  (make-vect (* s (xcor-vect v))
             (* s (ycor-vect v))))
 
(define (sub-vect v1 v2)
  (add-vect v1
            (scale-vect -1 v2)))

Tests:

(add-vect v1 v2)

Output:

(1 . 9)
(scale-vect 2 v1)

Output:

(4 . 6)
(scale-vect -1 v2)

Output:

(1 . -6)
(sub-vect v1 v2)

Output:

(3 . -3)
Personal tools