SICP問題1.32

線形再帰な accumulate

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

反復手続きな accumulate

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

sum を accumulate で書き直し

(define (sum term a next b)
  (define (combiner x y) (+ x y))
  (define (null-value) 0)
  (accumulate combiner (null-value) term a next b))

product を accumulate で書き直し

(define (product term a next b)
  (define (combiner x y) (* x y))
  (define (null-value) 1)
  (accumulate combiner (null-value) term a next b))

もう少しすっきり sum を accumulate で書き直し

(define (sum term a next b)
  (accumulate + 0 term a next b))

もう少しすっきり product を accumulate で書き直し

(define (product term a next b)
  (accumulate * 1 term a next b))