#lang racket (require "stream-base.rkt") ; square root approximations sequence (define (square x) (* x x)) (define (average a b) (/ (+ a b) 2)) ; improve the estimate. a better square root is somewhere between ; the current estimate, and x / estimate. (define (sqrt-improve estimate x) (average estimate (/ x estimate))) ; a stream of increasingly better approximations to square root of x (define (sqrt-stream x) ; a definition local to the sqrt-stream function ; the approximation stream is initial estimate 1 followed by a ; stream generated by improving the approximations. The map is ; generating the next approximation in the sequence by improving ; the current one, thus always providing another term in the ; stream if needed. (define approximations (s-cons 1.0 ; force floating point instead of rational (s-map (lambda (estimate) (sqrt-improve estimate x)) approximations))) ; return the stream of approximations approximations) ; try ; (define s2 (sqrt-stream 2)) ; (s-ref s2 5)