This preview shows pages 1–5. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Sheet1 Page 1 CS 61AWeek 2 Homework Solutions Exercise 1.31(a): (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (product term a next b) (define (iter a result) (if (> a b) result (iter (next a) (* result (term a))))) (iter a 1)) (define (! n) (product (lambda (x) x) 1 1+ n)) (define (pi terms) (* 4 (product (lambda (x) (/ (* 2 (1+ (floor (/ x 2)))) (1+ (* 2 (ceiling (/ x 2)))))) 1 1+ terms))) (define (pi terms) (* 4 (product (lambda (x) (/ (* (1+ x) (1+ x)) (* x x) )) 3 (lambda (x) (+ x 2)) terms ))) Sheet1 Page 2 Exercise 1.32(a): (define (accumulate combiner nullvalue term a next b) (if (> a b) nullvalue (combiner (term a) (accumulate combiner nullvalue term (next a) next b)))) (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)) (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: (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) Sheet1 Page 3 next b predicate)))) (define (filteredaccumulate combiner nullvalue term a next b predicate) (define (iter a result) (cond ((> a b) result) ((predicate a) (iter (next a) (combiner (term a) result))) (else (iter (next a) result)))) (iter a nullvalue)) (define (sumsqprime a b) (define (square x) (* x x)) (filteredaccumulate + 0 square a 1+ b prime?)) (define (prodofsomenumbers n) (filteredaccumulate * 1 (lambda (x) x) 1 1+ n (lambda (x) (= 1 (gcd x n))))) Exercise 1.40: (define (cubic a b c) (lambda (x) (+ (* x x x) (* a x x) (* b x) c))) Exercise 1.41: (define (double f) (lambda (x) (f (f x)))) Why does (((double (double double)) inc) 5) return 21 and not 13? The crucial point is that DOUBLE is not associative. > (((double (double double)) inc) 5) 21 > ((double (double (double inc))) 5) 13 DOUBLE turns a function into one that applies the function twice. Sheet1 Page 4 (DOUBLE DOUBLE) turns a function into one that applies the function four times....
View
Full
Document
This note was uploaded on 09/14/2009 for the course PEIS 100 taught by Professor Mckenzie during the Spring '08 term at Berkeley.
 Spring '08
 mckenzie

Click to edit the document details