A Sample Scheme Program
This is a scheme program from SICP that demonstrates the elegance of Scheme; it is the definition of a procedure that finds the roots of equations using the half-interval method:
(define (search f neg-point pos-point)
(let ((midpoint (average neg-point pos-point)))
(if (close-enough? neg-point pos-point)
midpoint
(let ((test-value (f midpoint)))
(cond ((positive? test-value)
(search f neg-point midpoint))
((negative? test-value)
(search f midpoint pos-point))
(else midpoint))))))
(define (close-enough? l r)
(< (abs (- l r)) 0.0001))
(define (average l r)
(/ (+ l r) 2))
;This is the entry point to the program
(define (half-interval-method f a b)
(let ((a-value (f a))
(b-value (f b))
(cond ((and (negative? a-value) (positive? b-value))
(search f a b))
((and (negative? b-value) (positive? a-value))
(search f b a))
(else
(error "Values are not of opposite sign" a b)))))