7
\$\begingroup\$

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?

asked Jun 27, 2011 at 1:58
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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.
answered Mar 7, 2012 at 21:03
\$\endgroup\$
1
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ Commented Dec 4, 2012 at 23:44
1
\$\begingroup\$

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.

answered Sep 17, 2013 at 17:33
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.