問題1.32a、問題1.32b – SICP(計算機プログラムの構造と解釈)その15

問題1.32 a

再帰的プロセスの 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))

; sum-integers
(define (sum-integers a b)
  (define (identify x) x)
  (define (inc x) (+ x 1))
  (sum identify a inc b))

(sum-integers 1 10)

gosh> sum-integers
gosh> 55

; sum-cubes
(define (sum-cubes a b)
  (define (cube x) (* x x x))
  (define (inc x) (+ x 1))
  (sum cube a inc b))

(sum-cubes 1 10)

gosh> sum-cubes
gosh> 3025

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

; factorial
(define (factorial n)
  (define (inc x) (+ x 1))
  (define (term i) i)
  (product term 1 inc n))

(factorial 10)

gosh> factorial
gosh> 3628800

問題1.32 b

反復的プロセスの accumulate

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

; sum-integers
(define (sum-integers a b)
  (define (identify x) x)
  (define (inc x) (+ x 1))
  (sum identify a inc b))

(sum-integers 1 10)

gosh> sum-integers
gosh> 55

; sum-cubes
(define (sum-cubes a b)
  (define (cube x) (* x x x))
  (define (inc x) (+ x 1))
  (sum cube a inc b))

(sum-cubes 1 10)

gosh> sum-cubes
gosh> 3025

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

; factorial
(define (factorial n)
  (define (inc x) (+ x 1))
  (define (term i) i)
  (product term 1 inc n))

(factorial 10)

gosh> factorial
gosh> 3628800
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»