6.001 Recitation #4 – Feb 14, 2003

 

RI: Konrad Tollmar

www.ai.mit.edu/6001

 

Data abstractions

Pairs and lists

Common list operations

 

1. Printed representation.

(define x (list 1 2))

(define y (list (list 1 2) (list 1 2))

(define z (list x x))

 

 

X ==> (1 2)

 

Y ==> ((1 2) (1 2))

 

Z ==> ((1 2) (1 2))

 

Be aware of that the box & pointer diagram for Y & Z are different!

 

 

2. cons, car, cdr.

 

(cons 1 nil) ==> (1)

(cons 1 (cons 2 nil)) ==> (1 2)

 

(define thing (cons (cons 1 nil) (cons 2 (cons 3 nil))))

 thing ==> ((1) 2 3)

 

(car thing) ==>  (1)

(cdr thing) ==> (2 3)

(car (car thing)) ==> 1

(car (cdr (cdr thing))) ==> 3

 

(car (cons (+ 1 2) (- 3 4)))  ==> 3      

(cdr 6) ==> error

(cdr (car (cons (cons 1 2) (cons 3 4)))) ==> 3

(pair? #t)  ==> #f

(pair? (car (cons 1 2))) ==> #f

(pair? (cons (+ 1 2) (car (cons (3 4))))) ==> #t

3. lenght, list-ref, append.

x => (())

y => (1 2 3)

z => (1 (2 3) ((4)))

w => (1 2 3 4 5)

 

 

(length x) ==> 1

(length y) ==> 3

(length z) ==> 3 (length don’t travers the three)

(list-ref z 2) ((4))

(append x y) (() 1 2 3)

(cons x y) (()) 1 2 3)

 

4. Try substitution on a list procedure.

(define (map proc lst)

  (if (null? lst)

      nil

      (cons (proc (car lst))

            (map proc (cdr lst)))))

 

 

(map square (1 2 3))

 

 

5. Data abstractions

 

You and your partner have been asked to build a small vector package. Firstly should you together define an interface to this package, i.e. the constructor, selectors and operations. Secondly, one of you implements the constructors and the selectors, while your partner implement a couple of vector operations. Last verify that your code work together and prepare a brief presentation.