计算机如何读取程序

How the computer read the program

当我阅读 SICP 时,这是一个非常初级但普遍的问题。我对计算机的工作方式感到困惑 阅读程序。我理解计算机将程序读取为一层或嵌套系统,这意味着 lower layer 无法从 upper layer 读取 item 但当我遇到这个程序时显然不是这样 在 SICP 中:

(define balance 100)
(define (withdraw amount)
        (if (>= balance amount)
            (begin (set! balance(- balance amount))
             balance)
         "Insufficient funds"))

如你所见,平衡是我在上层可以处理的一些项目,而我可以看到下层程序仍然可以读取它,所以这是错误的,所以我想知道计算机是如何读取程序的

withdrawbalance 都定义在 相同级别 balance 不在“上”级别),并且balancewithdraw之前被定义了,所以withdraw自然可以“看到”balance.

解释器将所有 top-level 定义添加到同一个环境中,一个定义可以引用同一级别的另一个定义,只要它之前已经定义过,例如:

(define x 10)
(define y (+ 6 x))

这也适用于嵌套过程。嵌套过程可以“看到”它上面 的所有定义。例如,这是有效的:

(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

在上面的例子中,g内部ff之外没有任何东西“看到”g,但是 g 可以“看到”其上方的所有内容。