問題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)))) ; sum (define (sum term a next b) (accumulate + 0 term a next b)) (define (sum-cubes a b) (sum (lambda (x) (* x x x)) a (lambda (n) (+ n 1)) b)) ; product (define (product term a next b) (accumulate * 1 term a next b)) (define (factorial n) (product (lambda (x) x) 1 (lambda (n) (+ n 1)) n))
accumulate反復的手続き
(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)) ; 検算用(Gaucheのテストモジュールを使えばいいのか) (define (product-iter term a next b) (accumulate-iter * 1 term a next b)) (define (factorial n) (product-iter (lambda (x) x) 1 (lambda (n) (+ n 1)) n))