I'm attempting to go through the SICP book, and I've run into a problem trying to implement the Square root method laid out in the book.
My code:
(define (square-root-loop g x)
(if (good-enough? g x)
g
(squre-root-loop (improve-sqrt-guess g x)
x)))
(define (improve-sqrt-guess g x)
(average-guess g (/ x g)))
(define (average-guess x y)
(/ (+ x y) 2))
(define (good-enough? g x)
(< (abs (- (square g) x)) 0.001))
(define (sqrt x)
(square-root-loop 1.0 x))
However, when I call the sqrt procedure, eg: (sqrt 9) , I get the following error:
;Unbound variable: squre-root-loop
;To continue, call RESTART with an option number:
; (RESTART 11) => Specify a value to use instead of squre-root-loop.
; (RESTART 10) => Define squre-root-loop to a given value.
; (RESTART 9) => Return to read-eval-print level 9.
; (RESTART 8) => Return to read-eval-print level 8.
; (RESTART 7) => Return to read-eval-print level 7.
; (RESTART 6) => Return to read-eval-print level 6.
; (RESTART 5) => Return to read-eval-print level 5.
; (RESTART 4) => Return to read-eval-print level 4.
; (RESTART 3) => Return to read-eval-print level 3.
; (RESTART 2) => Return to read-eval-print level 2.
; (RESTART 1) => Return to read-eval-print level 1.
The code is pretty much exactly as it is in the book, so I don't what's up. (I have passed the procedures to the Evaluator after defining them, so they should be defined. 'abs' has already been defined as well.)
I'm running MIT-Scheme on emacs. Screenshot
To close this question, I will write up a formal answer instead of having the answer as a comment.
The problems are that
(1) square-root-loop
is spelled incorrectly in the recursive call,
it is referred to as squre-root-loop
;
(2) square
is missing, it should be defined as (define (square x) (* x x))
.
Be careful of the naming.
The functions are both named sqrt
and square-root
, use the same name.
So, square-root-loop
should be sqrt-loop
.
Some of the function names include reference to square root, others don't.
Apparently, SICP doesn't introduce letrec
until very late, but when you learn about it, try to gather the functions into an inner scope and let only the outer function mention square root to avoid redundancy.