SICP問題3.64

引数としてストリームと数値(許容誤差)を取る手続きstream-limitを定義せよ。
stream-lmitはストリームを調べて会い続く二つの要素が絶対値で許容誤差より小さくなるのを見つけ、その二つの要素の二番目を返す。
いい加減stream-refを入力するのに飽きたのでこんな手続きを定義

(define (stream-ref-range s from to)
  (if (< from to)
      (begin
        (display (stream-ref s from))
        (newline)
        (stream-ref-range s (+ from 1) to))))

stream-limitの定義

(define (stream-limit s tolerance)
  (let ((item1 (stream-car s))
        (item2 (stream-car (stream-cdr s))))
    (if (< (abs (- item1 item2)) tolerance)
        item2
        (stream-limit (stream-cdr s) tolerance))))

テスト

(define (sqrt x tolerance)
  (stream-limit (sqrt-stream x) tolerance))
(stream-ref-range (sqrt-stream 2) 0 20)
; 1.0
; 1.5
; 1.4166666666666665
; 1.4142156862745097
; 1.4142135623746899
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; 1.414213562373095
; #<undef>

(sqrt 2 0.01)
; 1.4142156862745097

(sqrt 2 0.001)
; 1.4142135623746899