Trying out exercises from "Structure and Interpretation of Computer Programs" second edition
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.

33 lines
845 B

#! /usr/bin/racket
#lang racket/base
(define (square n)
(* n n))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(define (next iterator)
(if (= iterator 2) 3 (+ iterator 2)))
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(define (filtered-accumulate combiner null-value predicate term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (if (predicate a) (term a) null-value) result))))
(iter a null-value))
(define (range-sum-of-primes a b)
(filtered-accumulate + 0 prime? (lambda (x) x) a (lambda (x) (+ 1 x)) b))
(range-sum-of-primes 2 10)