Code

#lang racket

(require "common.scm")

(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 result (term a))))
      (else (iter (next a) (combiner result null-value)))))
  (iter a null-value))

(define (smallest-divisor n)
  (find-divisor n 2))

(define (find-divisor n test-divisor)
  (define (next n)
    (if (= n 2) 3 (+ n 2)))
  (cond ((> (square test-divisor) n) n)
        ((divides? test-divisor n) test-divisor)
        (else (find-divisor n (next test-divisor)))))

(define (prime? n)
  (= n (smallest-divisor n)))

(define (relatively-prime? a b)
  (= 1 (gcd a b)))

(define n 9)
(define (relatively-prime-n? m) (relatively-prime? n m))

; tests

(filtered-accumulate + 0 identity 2 inc 10 even?) ; 2+4+6+8+10 = 30
(filtered-accumulate + 0 square 2 inc 10 prime?) ; 2^2+3^2+5^2+7^2 = 4+9+25+49 = 87
(filtered-accumulate * 1 identity 2 inc n relatively-prime-n?) ; 2*4*5*7*8 = 2240

Output

30
87
2240