Search code examples
scheme

Unbound variable error in cube root function


The code is as follows:

(define (square x) (* x x))

(define (abs x) (if (< x 0) (- x) x))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
    guess
    (sqrt-iter (improve guess x) x)))

(define (average x y) (/ (+ x y) 2))

(define (improve guess x) (average guess (/ x guess)))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (sqrt x) (sqrt-iter 1.0 x))

(define (cube x) (* x x x))

(define (cubrt-itr y x) (if (good-enough y x) y (cubrt-iter (improve! y x) x)))

(define (improve! y x) ((/ (+ (* 2 y) (/ x (square y))) 3)))

(define (good-enough y x) (< (abs (- (cube y) x)) 0.001))

(define (cubrt x) (cubrt-iter 1.0 x))

Please check the code it works for square root e.g when I type in (sqrt 144) it gives me 12 but that is not the case for the cube root procedure - it gives me the error

ERROR IN cubrt, console@18:20 -- Unbound variable error

Is there a way I can write this code better. Where am I going wrong?


Solution

  • You have defined cubrt-itr, but are calling cubrt-iter. Such mistakes might be more obvious if you used less abbreviated names for your variables.