some solutions for MIT Press's "structure and interpretation of computer programs", I guess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
933 B

(define (cube x)
(* x x x))
(define (inc x)
(+ x 1))
(define (identity x) x)
(define (filtered-accumulate combiner null-value term a next b predicate)
(define (iter a result)
(cond ((> a b) result)
((predicate a) (iter (next a) (combiner result (term a))))
(else (iter (next a) result))))
(iter a null-value))
(define (square x)
(* x x))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(define (sum-sq-prime a b)
(filtered-accumulate + 0 square a inc b prime?))
(define (prod-relative-prime n)
(define (relative-prime? a)
(= 1 (gcd a n)))
(filtered-accumulate * 1 identity 1 inc n relative-prime?))