6.001
Recitation #5 – Feb 19, 2003
RI: Konrad Tollmar
• Common list operations
• Types
• Order of growth
• Data abstractions
1. Revisit - Pairs and lists
(define
doublefun
(list (cons (+ 2 4) nil) (cons 0 (cons 0 (cons 1
nil)))))
2. Common list operations
x
=> (())
y
=> (1 2 3)
z
=> (1 (2 3) ((4)))
w
=> (1 2 3 4 5)
Write the procedure copy-some
that copies the first n elements of a list, i.e.
(copy-some 3 (list 1 2 3 4 5)) ==> (1 2 3)
4. What is the type?
5. What are the types of these procedures?
1. length
2. list-ref
3. append
For each, find simplest and slowest growing f for which R(n)=Q(f(n))
R(n)=6
R(n)=n2 + 3
R(n)=6*n3 + 3*n2 + 7n + 100
R(n)=23n+7
What is simplest expression for the order of growth of
running time
of procedure copy-some, last-k, mul1 & mul2? What about space?
(define (last-k k lst)
(if (=
(length lst) k) lst (last-k k (cdr lst))))
(define
(mul1 n m)
(if (= n 0) 0 (+ m (mul1 (- n 1) m))))
(define
(mul2 n m)
(define (help count ans)
(if (= count 0)
ans
(help (- count 1) (+ m
ans))))
(help n 0))
1. Q(1), 2. Q(log n), 3. Q(n), 4. Q(2^n)
8. Reduce a calculation from Q(n) to Q(log
n)
Write a procedure mul3 that computes m*n in Q(log n) time. Write similar procedure mul4 that does the same job and in Q(1) space.
Hint: n*m = 2 * ( (n / 2) * m) if n even, n*m = m + ((n-1) * m) if n odd.
9. 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.