CS61A, Spring 1992
Midterm #1
Question 1 (4 points):
What will Scheme print in response to the following expressions? Assume
that they are typed in sequence, so definitions affect later interactions.
If an expression produces an error message, you may just say ``error''; you
don't have to provide the exact text of the message.
(* (+ 2 3) (- 7 (* 5 0))))
(if (+ 2 3) (+ 4 5) (+ 6 7))
(define six 6)
(let ((- +)
(ringo six))
(- six ringo))
(- 6 4)
(first (butlast (last (butlast '(the long and winding road)))))
(+ (bl 472) (first 38))
(lambda (a b) (word b (first a)))
((lambda (d c) (word (last c) d)) 'here 'not)
Question 2 (5 points):
Write a procedure add-numbers that takes a sentence as its argument.
Some of the words in the argument sentence might be numbers. The procedure
should return the sum of those numbers. For example:
> (add-numbers '(8 days 1 week))
9
> (add-numbers '(76 trombones, 4 calling birds, and 2 turtle doves))
82
> (add-numbers '(all you need is love))
0
You may use the primitive predicate number? in your procedure.
Question 3 (5 points):
Implement the following function as a Scheme procedure:
+-
| 1, if b = 0;
f(a,b) = |
| a x f(a, b - 1) if b > 0.
+-
Also, explain in one English sentence the mathematical meaning of
this function.
Question 4 (5 points):
Consider the function
(define (reciprocal x) (/ 1 x))
This function doesn't work too well if its argument is zero. Suppose we
want the function described in words this way: ``If the argument is zero,
return zero; otherwise, use reciprocal.'' We'd like to be able to create
that function this way:
(define reciprocal-unless-zero (choose-function zero?
(lambda (x) x)
reciprocal) )
Write the function choose-function. It takes three arguments,
all of which are functions of one argument. The first argument is a
predicate function. Let's call the arguments pred, f1,
and f2. Choose-function returns a new function of
one argument, such that if pred of that argument is true, the
value is the result of applying f1 to the argument; if not,
the result of applying f2.
> (define funny-fn (choose-function even? first last))
> (funny-fn 376)
3
> (funny-fn 495)
5
Take a peek at the
solutions