exercise-32.scm (2154B)
1 (define-library (sicp solutions chapter-1 exercise-32) 2 (import (scheme base)) 3 (export 4 iterative-accumulate 5 iterative-product 6 iterative-sum 7 recursive-accumulate 8 recursive-product 9 recursive-sum 10 ) 11 12 (begin 13 (define (iterative-accumulate combiner null-value term a next b) 14 (define (iter a result) 15 (if (> a b) 16 result 17 (iter (next a) (combiner (term a) result)))) 18 (iter a null-value)) 19 20 (define (recursive-accumulate combiner null-value term a next b) 21 (if (> a b) 22 null-value 23 (combiner (term a) 24 (recursive-accumulate combiner 25 null-value 26 term 27 (next a) 28 next 29 b)))) 30 31 (define iterative-sum 32 (lambda (term a next b) 33 (iterative-accumulate (lambda (acc x) 34 (+ acc x)) 35 0 36 term 37 a 38 next 39 b))) 40 (define iterative-product 41 (lambda (term a next b) 42 (iterative-accumulate (lambda (acc x) 43 (* acc x)) 44 1 45 term 46 a 47 next 48 b))) 49 50 (define recursive-sum 51 (lambda (term a next b) 52 (recursive-accumulate (lambda (acc x) 53 (+ acc x)) 54 0 55 term 56 a 57 next 58 b))) 59 (define recursive-product 60 (lambda (term a next b) 61 (recursive-accumulate (lambda (acc x) 62 (* acc x)) 63 1 64 term 65 a 66 next 67 b)))))