2015/10/08

SICP 問題1.33

;; 再帰的プロセスで
(define (filtered-accumulate filter combiner null-value term a next b)
  (cond ((> a b) null-value)
        ((filter a) (combiner (term a)
                              (filtered-accumulate filter combiner null-value
                                                   term (next a) next b)))
        (else (filterd-accumulate filter combiner null-value term (next a) next b))))

;; 反復的プロセスで
(define (filtered-accumulate filter combiner null-value term a next b)
  (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))

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

(define (product-disjoint-n n)
  (define (disjoint-n? a)
    (define (gcd a b)
      (if (= b 0)
          a
          (gcd b (remainder a b))))
    (= (gcd a n) 1))
  (filtered-accumulate disjoint-n? * 1 (lambda (a) a) 1 1+ n))

© 2022 wat-aro