schemeracketr6rs

Why do all procedures have to be defined before the compiler sees them?


For example, take a look at this code (from tspl4):

(define proc1
  (lambda (x y)
    (proc2 y x)))

If I run this as my program in scheme...

#!r6rs
(import (rnrs))

(define proc1
  (lambda (x y)
    (proc2 y x)))

I get this error:

expand: unbound identifier in module in: proc2

...This code works fine though:

#!r6rs
(import (rnrs))

(define proc2
  +)

(define proc1
  (lambda (x y)
    (proc2 y x)))

(display (proc1 2 3)) ;output: 5

Solution

  • They all have to be defined in the same module (= "library" in r6rs lingo). But you can define them in any order you want -- for example, in your last snip you can swap the two definitions and it will work fine. But note that you cannot put the definitions after the display line -- this is an expression that uses their value, so if you move the function definitions after it, you'll get a runtime error. (Note the fact that it's a runtime error rather than a compile-time one.)