This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Little help about define procedure

4 posts · 8079 views

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:
(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:
(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

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.
I'm the author of two useless languages that uses BF as target machine.
Currently I'm planning a Scheme compiler :p

Re: Little help about define procedure

OK, I see , thanks for your detailed explanations~

Re: Little help about define procedure

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.