Open Source WEB

##(link2sicp "book-Z-H-12.html#%_thm_1.33" "Exercise 1.33")

解答例

再帰プロセス版 filtered-accumulate

(define (filtered-accumulate combiner null-value term filter a next b)
  (cond ((> a b) null-value)
        ((filter a)
          (combiner
            (term a)
            (filtered-accumulate
              combiner null-value term filter (next a) next b)))
        (else
          (filtered-accumulate
            combiner null-value term filter (next a) next b))))

反復プロセス版 filtered-accumulate

(define (filtered-accumulate combiner null-value term filter a next b)
  (cond ((> a b) null-value)
        ((filter a)
         (filtered-accumulate
          combiner (combiner null-value (term a)) term filter (next a) next b))
        (else 
         (filtered-accumulate
          combiner null-value term filter (next a) next b))))

a. 区間 a, b の素数の二乗の和

(define (sum-of-square-primes a b)
  (filtered-accumulate + 0 square prime? a inc b))

b. n と互いに素で、n より小さい正の整数の積

(define (product-of-irreducibles n)
  (define (primeWith? n) 
    (lambda (x) (= (gcd n x) 1)))
  (filtered-accumulate * 1 identity (primeWith? n) 1 inc (- n 1)))

コード

##(sicp-answer-code "ex-1.33.scm")

このサイトは、 IPA の「平成15年度オープンソフトウエア活用基盤整備事業」 の委託事業として開発されたKahuaで試験的に運用しております。

Copyright (c) 2004-2007 株式会社タイムインターメディア About Us