sicp/1_32.sch

42 lines
736 B
Scheme

(define (accumulate-rec combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
(define (accumulate-iter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner result (term a)))))
(iter a null-value))
;(define accumulate accumulate-rec)
(define accumulate accumulate-iter)
(define (product term a next b)
(accumulate
(lambda (x y) (* x y))
1
term
a
next
b))
(define (sum term a next b)
(accumulate
(lambda (x y) (+ x y))
0
term
a
next
b))
(define (fact n)
(product
(lambda (x) x)
1
(lambda (x) (+ x 1))
n))