Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

From SICP:

Exercise 3.64. Write a procedure stream-limit that takes as arguments a stream and a number (the tolerance). It should examine the stream until it finds two successive elements that differ in absolute value by less than the tolerance, and return the second of the two elements. Using this, we could compute square roots up to a given tolerance by

(define (sqrt x tolerance)
  (stream-limit (sqrt-stream x) tolerance))

I wrote this answer:

(define (stream-limit s tol)
  (if (stream-null? s) 
      (error "End of stream found before limit reached:" tol)
      (let* ((a (stream-car s))
             (b (stream-car (stream-cdr s)))
             (diff (abs (- a b))))
        (if (> tol diff) b (stream-limit (stream-cdr s) tol)))))

Can it be improved?

share|improve this question

Looks fine to me. I would only suggest changing (> tol diff) to (< diff tol) because it reads more like the problem specification and is easier to understand.

share|improve this answer

Looks good. Is it OK to just say it looks good? If it's not, here are two comments:

  • Why do you use let* here? Isn't let enough?
  • You could define stream-cadr.
share|improve this answer
The initializer for diff uses the values of a and b. Since let doesn't create the variable bindings until after evaluating all of the initializer expressions, it won't work here. – rob mayoff Dec 4 '12 at 23:44

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.