This preview shows pages 1–3. Sign up to view the full content.
CS 61A
Week 2
Homework Solutions
Exercise 1.31(a):
;; you only needed to hand in one version
;; but by now you're ready to understand both:
;; recursive version:
(define (product term a next b)
(if (> a b)
1
;; Note multiplicative identity is 1 not 0
(* (term a)
(product term (next a) next b))))
;; iterative version:
(define (product term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* result (term a)))))
(iter a 1))
;; factorial
(define (! n) (product (lambda (x) x) 1 1+ n))
;; pi
;; You have to run a few hundred terms to get a good approximation.
;; There are several possible ways to arrange the terms.
Here is one
;; way, in which the first term is 2/3, the second is 4/3, etc.
(define (pi terms) (* 4 (product
(lambda (x) (/ (* 2 (1+ (floor (/ x 2))))
(1+ (* 2 (ceiling (/ x 2))))))
1 1+ terms)))
;; Here is another way, in which the first term is (2/3)*(4/3), the
;; second is (4/5)*(6/5), etc.
Notice that the value of a starts at
;; 3 and is increased by 2 for each new term.
(define (pi terms) (* 4 (product
(lambda (x) (/ (* (1+ x) (1+ x))
(* x x) ))
3
(lambda (x) (+ x 2))
terms )))
;; If you try to make it 2 * (4/3) * (4/3) * (6/5) * (6/5) * .
.. you'll
;; get the wrong answer, because you'll have one more number in the
;; numerator than in the denominator.
Exercise 1.32(a):
;; you only needed to hand in one version
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document;; recursive form
(define (accumulate combiner nullvalue term a next b)
(if (> a b)
nullvalue
(combiner (term a)
(accumulate combiner nullvalue term (next a) next b))))
;; iterative form
(define (accumulate combiner nullvalue term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))))
(iter a nullvalue))
;; sum and product
(define (sum term a next b) (accumulate + 0 term a next b))
(define (product term a next b) (accumulate * 1 term a next b))
Exercise 1.33:
;; The problem only requires one version but this too can be
;; recursive or iterative.
Recursive version:
(define (filteredaccumulate combiner nullvalue term a next b predicate)
(cond ((> a b) nullvalue)
((predicate a)
(combiner (term a)
(filteredaccumulate combiner
nullvalue
term
(next a)
next
b
predicate)))
(else (filteredaccumulate combiner
nullvalue
term
(next a)
next
b
predicate))))
;; Iterative version:
(define (filteredaccumulate combiner nullvalue term a next b predicate)
This is the end of the preview. Sign up
to
access the rest of the document.
 Fall '08
 Harvey

Click to edit the document details