SICP問題1.33

線形再帰な filtered-accumulate

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

反復手続きな filtered-accumulate

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

区間a, bの素数の二乗の和(prime?述語は持っていると仮定する)

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

n と互いに素で, n より小さい正の整数(つまり i < n で GCD(i, n) = 1なる全整数 i)の積

(define (product-gcd a b)
  (define (gcd? x) (if (= (gcd x b) 1) #t #f))
  (define (term i) i)
  (filtered-accumulate * 1 term a inc b gcd?))