Friday, September 5, 2008

sicp-exercise-1.32-1.33

Exercise 1.32

Recursive process

(define (accumulate combiner null-value a b term next)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner null-value (next a) b term next))))



Iterative process

(define (accumulate combiner null-value a b term next)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))))
(iter a null-value))



Define sum and product.

(define (sum a b term next)
(define (add x y) (+ x y))
(accumulate add 0 a b term next))


(define (product a b term next)
(define (mul x y) (* x y))
(accumulate mul 1 a b term next))


Exercise 1.33


(define (filtered-accumulate pass-filter? combiner null-value term a next b)
(if (> a b)
null-value
(combiner (if (pass-filter? a)
(term a)
null-value)
(filtered-accumulate pass-filter?
combiner
null-value
term
(next a)
next
b))))


Define sum of the squares of the prime numbers in [a, b],
and product of all positive integers less than n that are relatively prime to n.

(define (sum-prime-squares a b)
(filtered-accumulate prime? add 0 square a inc b))

;;;;;;;;;;;;;
(define (relative-prime? x y)
(= (gcd x y) 1))

(define (product-reletive-prime n)
(define (filter x)
(relative-prime? x n))
(filtered-accumulate filter mul 1 identity 1 inc n))

0 comments:

Post a Comment