Chapter 2, Building Abstractions with Data

Section - 2.2 - Hierarchical Data and the Closure Property

Exercise 2.46


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#lang sicp

(#%require sicp-pict)

(define (make-vect x y)
    (cons x y)
)

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

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

(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 v scale)
   (make-vect (*
                 scale
                 (xcor-vect v)
              )
              (*
                 scale
                 (ycor-vect v)
              )
   )
)

Test/Output:

1
2
3
4
5
6
7
8
9
> (define v1 (make-vect 1 2))
> (define v2 (make-vect 10 20))
> (add-vect v1 v2)
(mcons 11 22)
> (sub-vect v1 v2)
(mcons -9 -18)
> (scale-vect v1 10)
(mcons 10 20)
>