1

When I write code in Dr Racket, I got error message

unsaved-editor:8:2: define: expected only one expression for the function body, but found 3 extra parts in: (define (improve guess x) (average guess (/ x guess)))

But this code can run in Racket or repl.it.

I want to know why error is happening in Dr Racket and is my code really wrong?

My code is this:

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

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

(define (sqrt1 x)
  (define (good-enough? guess x)
    (< (abs (- (square guess) x)) 0.001))
  (define (improve guess x)
    (average guess (/ x guess)))
  (define (sqrt-iter guess x)
    (if (good-enough? guess x)
        guess
        (sqrt-iter (improve guess x) x)))
  (sqrt-iter 1.0 x))

(sqrt1 9)
rsm
  • 2,530
  • 4
  • 26
  • 33
Namk0207
  • 45
  • 5

1 Answers1

1

Your code is OK for Scheme/Racket. However Student Language is a subset of Scheme, highly limited so it's easier for beginners. It's also used in How To Design Programs book. You can read more about Student Languages (actually there is five of them) on https://docs.racket-lang.org/htdp-langs/index.html.

In case of define there are important limitations:

  1. You can have only one expression in the function body.
  2. In function body you can only use expressions, not definitions (so no define inside define).

To make your code valid for Student Language, depending on Level (Beginner, Intermediate etc), you can:

  • use letrec* or local instead of define for all local definitions

or

  • define good-enough, improve and sqrt-iter as top level functions.
rsm
  • 2,530
  • 4
  • 26
  • 33
  • To make code valid for student languages you can also move internal definitions into [`local`](https://docs.racket-lang.org/htdp-langs/intermediate.html?q=local#%28form._%28%28lib._lang%2Fhtdp-intermediate..rkt%29._local%29%29). Moving existing `define` forms into `local` will be easier than rewriting them into a letrec, especially for function definitions – Alex Knauth Sep 27 '19 at 13:35
  • @AlexKnauth Depends on the student language required. The two starting with "Beginner" doesn't have `local` – Sylwester Sep 27 '19 at 18:44
  • The two starting with "Beginner" don't have letrec or let, either. Any *SL that has letrec, also has local, from Intermediate Student Language up – Alex Knauth Sep 27 '19 at 21:50
  • @AlexKnauth and Sylwester - Thanks for the comments, I modified my answer acordingly. – rsm Sep 28 '19 at 01:15