CSE341 Key to Final, Autumn 2007 handout #23
1. Scheme expressions.
Part A:
(define a 2)
(define b 4)
(define c 8)
(let ((a (+ a c))
(b (+ a b)))
(list a b c))
(10 6 8)
Part B:
(define a 4)
(define b 8)
(define c 12)
(let* ((a (+ a c))
(c (+ a b)))
(list a b c))
(16 8 24)
Part C:
(define a '(b))
(define b (cons a '(b c)))
(set-car! a 12)
(set! a 5)
(set-car! (cdr b) a)
(list a b)
(5 ((12) 5 c))
Part D:
(define a '(1 2))
(define b (cons 8 a))
(define c (append b a))
(set-car! (cdr b) 16)
(set-car! b 24)
(list a b c)
((16 2) (24 16 2) (8 1 2 16 2))
2. One possible solution appears below.
(define (cube-sum n)
(cond ((< n 0) (error "negative argument"))
((= n 0) 0)
(else (+ (* n n n) (cube-sum (- n 1))))))
3. One possible solution appears below.
(define (consecutive lst)
(cond ((null? lst) #t)
((null? (cdr lst)) #t)
(else (and (= (cadr lst) (+ 1 (car lst)))
(consecutive (cdr lst))))))
4. One possible solution appears below.
(define (powers n m)
(define (helper count power lst)
(if (= count 0)
lst
(helper (- count 1) (* power m) (append lst (list power)))))
(if (< n 0)
(error "negative argument")
(helper n m ())))
5. One possible solution appears below.
(define (vector-product lst1 lst2)
(cond ((and (null? lst1) (null? lst2)) ())
((or (null? lst1) (null? lst2))
(error "lists of different length"))
(else (cons (* (car lst1) (car lst2))
(vector-product (cdr lst1) (cdr lst2))))))
6. One possible solution appears below.
(define (transpose matrix)
(cond ((null? matrix) ())
((null? (car matrix)) ())
(else (cons (map car matrix) (transpose (map cdr matrix))))))
7. One possible solution appears below.
(define (matrix-product m1 m2)
(map (lambda (lst1) (map (lambda (lst2)
(foldl + 0 (vector-product lst1 lst2)))
(transpose m2))) m1))
8. Ruby expressions.
Part A:
x.each {|n| puts n + 1}
8
19
25
8
4
Part B:
for n in y do
puts n if n % 3 == 0
end
0
3
6
9
Part C:
x.map {|n| 2 * n + 1}
[15, 37, 49, 15, 7]
9. One possible solution appears below.
def minmax(lst)
min = lst[0]
max = lst[0]
for n in lst do
if n < min then
min = n
elsif n > max then
max = n
end
end
puts min
puts max
end
10. One possible solution appears below.
def add(x, y)
result = []
if x.length > y.length
max = x.length
else
max = y.length
end
max.times do |i|
n = 0
n += x[i] if x[i]
n += y[i] if y[i]
result.push n
end
result
end
11. One possible solution appears below.
class Array
def running_sum
sum = 0
for n in self
sum += n
yield sum
end
sum
end
end
12. One possible solution appears below.
class Array
def collapse
result = []
i = 0
while i < length - 1 do
result.push yield(self[i], self[i + 1])
i += 2
end
if length % 2 == 1 then
result.push self[-1]
end
result
end
end