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

From Drewiki
Jump to: navigation, search

Problem

Here are two possible constructors for frames:

(define (make-frame origin edge1 edge2)
  (list origin edge1 edge2))
 
(define (make-frame origin edge1 edge2)
  (cons origin (cons edge1 edge2)))

For each constructor supply the appropriate selectors to produce an implementation for frames.

Solution

Let's create some example vectors using the make-vector definition from exercise 2.46 (alternatively, we could use any other effective representation, of course):

(define (make-vect x y)
  (cons x y))
 
(define origin (make-vect 1 0))
 
(define edge1 (make-vect 2 2))
 
(define edge2 (make-vect 3 5))

The two make-frame definitions use similar, but not quite identical, representations for frames. Here's the first:

(define (make-frame origin edge1 edge2)
  (list origin edge1 edge2))
 
(make-frame origin edge1 edge2)

Output:

((1 . 0) (2 . 2) (3 . 5))


This definition produces a "proper" list, i.e., a sequence of pairs terminated by nil. Getting a particular vector is just a matter of caring and cdring.

(define (origin-frame frame)
  (car frame))
 
(define (edge1-frame frame)
  (cadr frame))
 
(define (edge2-frame frame)
  (caddr frame))

Test:

(define frame (make-frame origin edge1 edge2))
 
(origin-frame frame)

Output:

(1 . 0)
(edge1-frame frame)

Output:

(2 . 2)
(edge2-frame frame)

Output:

(3 . 5)


Here's the representation used by the second definition:

(define (make-frame origin edge1 edge2)
  (cons origin (cons edge1 edge2)))
 
(make-frame origin edge1 edge2)

Output:

((1 . 0) (2 . 2) 3 . 5)


It's the same as the first, except for the last cons cell. We only need to change the definition of edge2-frame to accomodate it:

(define (edge2-frame frame)
  (cddr frame))

Test:

(define frame (make-frame origin edge1 edge2))
 
(origin-frame frame)

Output:

(1 . 0)
(edge1-frame frame)

Output:

(2 . 2)
(edge2-frame frame)

Output:

(3 . 5)
Personal tools