exercise-33.scm (2071B)
1 (define-library (sicp solutions chapter-1 exercise-33) 2 (import (scheme base)) 3 (import (only (sicp solutions chapter-1 exercise-21) prime?)) 4 (export 5 iterative-filtered-accumulate 6 iterative-sum-of-squares 7 recursive-filtered-accumulate 8 recursive-sum-of-squares 9 ) 10 11 (begin 12 (define (iterative-filtered-accumulate predicate? combiner null-value term a next b) 13 (define (iter a result) 14 (if (> a b) 15 result 16 (if (predicate? a) 17 (iter (next a) 18 (combiner (term a) 19 result)) 20 (iter (next a) 21 result)))) 22 (iter a null-value)) 23 24 (define (iterative-sum-of-squares a b) 25 (iterative-filtered-accumulate prime? 26 + 27 0 28 (lambda (x) (* x x)) 29 a 30 (lambda (x) (+ 1 x)) 31 b)) 32 33 (define (recursive-filtered-accumulate predicate? combiner null-value term a next b) 34 (if (> a b) 35 null-value 36 (let ([recur (recursive-filtered-accumulate predicate? 37 combiner 38 null-value 39 term 40 (next a) 41 next 42 b)]) 43 (if (predicate? a) 44 (combiner (term a) recur) 45 recur)))) 46 47 (define (recursive-sum-of-squares a b) 48 (iterative-filtered-accumulate prime? 49 + 50 0 51 (lambda (x) (* x x)) 52 a 53 (lambda (x) (+ 1 x)) 54 b))))