Page 1 of 1

Little help about define procedure

Posted: Wed Apr 16, 2014 5:50 pm
by blackdiz
Hi everybody
I'm trying to study SICP. I use Dr.Racket and intall Neil Van Dyke's SICP Support for DrRacket. When I practice examples of the book, I bumped into something confused me.
The following codes are from the book and I use the procedure "sqrt" at beginning:

Code: Select all

(sqrt (+ 100 37))

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

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

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

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

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

(define (sqrt x)
  (sqrt-iter 1.0 x))
It worked perfactly well. But as for my understanding, you have to define a procedure before use it, right? So I don't understand how this can work?
And I do an experiment:

Code: Select all

(add 2 2)

(define (add x y)
  (test x y))

(define (test x y)
  (+ x y))
But this time the interpreter gave me "add: undefined; cannot reference undefined identifier", so I am totally confused about these results, can somebody explain what's going to me?

Thank you

Re: Little help about define procedure

Posted: Mon Apr 21, 2014 1:44 pm
by sylwester
sqrt is defined by the package so you are not using your own version when doing the first sqrt.
add is not included so you get an error.

You can tell by just type inn identifiers in the interactions window before you define them and like sqrt you'll see #<procedure:sqrt> with sqrt replaced by something else.
The reason for this is unknown but I imagine it has to do with sqrt being a standard procedure in RNRS Scheme and Racket. If the package is based on one R5RS (the closest language to R3RS which were used in SICP) you will have all of the R5RS procedure and syntax that are not in direct violation of R3RS.

Re: Little help about define procedure

Posted: Tue Apr 22, 2014 11:16 pm
by blackdiz
OK, I see , thanks for your detailed explanations~

Re: Little help about define procedure

Posted: Fri Apr 25, 2014 1:25 pm
by saulgoode
It is recommended practice in Scheme to never really DEFINE a variable that has already been DEFINEd. For interactive operations, it is permitted but it can be a source of problems/confusion. The example given isn't, IMO, especially well designed in that the 'sqrt' procedure that you define should be named 'mysqrt' or somesuch so as to avoid re-defining the "built-in" sqrt procedure.