Little help about define procedure

Discussion of Scheme and Racket

Little help about define procedure

Postby blackdiz » Wed Apr 16, 2014 5:50 pm

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)
      (sqrt-iter (improve guess 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
Posts: 2
Joined: Wed Apr 16, 2014 5:34 pm

Re: Little help about define procedure

Postby sylwester » Mon Apr 21, 2014 1:44 pm

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
Posts: 133
Joined: Mon Jul 11, 2011 2:53 pm

Re: Little help about define procedure

Postby blackdiz » Tue Apr 22, 2014 11:16 pm

OK, I see , thanks for your detailed explanations~
Posts: 2
Joined: Wed Apr 16, 2014 5:34 pm

Re: Little help about define procedure

Postby saulgoode » Fri Apr 25, 2014 1:25 pm

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.
Posts: 45
Joined: Tue Dec 14, 2010 1:39 am

Return to Scheme

Who is online

Users browsing this forum: No registered users and 1 guest