It is a quite elementary but general question when I am reading SICP. I get puzzled about how the computer read the program. I understand the computer read the program as a layer or nested system, which means the lower layer can't read the item from upper layer but it is obvious not true when I encounter this program in SICP:
(define balance 100)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance(- balance amount))
balance)
"Insufficient funds"))
As u can see, balance is some item I can treat on the upper layer, while I can see the lower layer program can still read that, so it is wrong, so I am wondering how the computer read the program
Both withdraw
and balance
are defined at the same level (balance
is not in an "upper" level), and balance
was defined before withdraw
, so it's natural that withdraw
can "see" balance
.
The interpreter adds all top-level definitions to the same environment, and one definition can refer to another at the same level as long as it's been previously defined, for example:
(define x 10)
(define y (+ 6 x))
This applies to nested procedures as well. A nested procedure can "see" all the definitions above it. For example, this is valid:
(define x 42)
(define (f) ; f and x are at the same level
(define (g) x) ; g is in a level below f, but sees x
(g))
(f)
=> 42
In the above example, g
is internal to f
, nothing outside f
"sees" g
, but g
can "see" all that's above itself.