目录
正在加载目录…
正在阅读专栏 SICP:Structure and Interpretation of Computer Programs 第 30 篇 · 共 80 篇 · 38%

SICP:3.1 Assignment and Local State

发布于 2026-09-18 08:47 · 最后编辑于 2026-09-18 10:20 · 版本 v2 · 字数 12,198 · 预计阅读 25 分钟 👁 13 次阅读

SICP:3.1 Assignment and Local State

本文逐段翻译 SICP 第二版 §3.1《Assignment and Local State》,覆盖 local state variables、set!、begin、message-passing objects、Monte Carlo simulation、referential transparency 与 imperative programming;保留原始公式图、Scheme code 和 Exercises 3.1–3.8。

TL;DR

  • Assignment 让 procedure 能通过 local state 记住历史,从而 model 随时间变化的 computational objects。
  • set! 与 local variables 结合,可以把 state 封装在 procedure closure 中;message passing 可进一步提供对 local operations 的访问。
  • 引入 assignment 后,同样 arguments 的两次调用可能产生不同结果,substitution model 不再足够。
  • Assignment 带来 modular state objects,也破坏 referential transparency,并引入 evaluation order、aliasing 和 imperative-programming pitfalls。

名词解释

名词含义本节对应物
state影响 object 当前 behavior 的历史信息bank account 的 balance
state variable保存足够历史信息以决定当前 behavior 的变量balance、x
assignment改变 name 所关联 value 的 operationset!
local state只由某个 computational object 直接持有的 statemake-account 的 balance
referential transparencyequivalent expressions 可以互相替换而不改变结果无 assignment 的 functional code
imperative programming大量使用 assignment 的 programming styleset! 更新 product / counter

目录

章节说明
3.1 Assignment and Local Statestate 与 assignment 的动机
3.1.1 Local State Variablesbank account 与 message passing
3.1.2 The Benefits of Introducing Assignmentrandom state 与 Monte Carlo
3.1.3 The Costs of Introducing Assignmentsubstitution model 与 identity
Sameness and changeobject identity
Pitfalls of imperative programmingassignment 顺序与并发
Exercises 3.1–3.8state-object exercises

3.1 Assignment and Local State

我们通常把 world 看作由 independent objects 组成,每个 object 都有一个会随时间改变的 state。如果一个 object 的 behavior 会受到自身 history 的影响,就说这个 object “has state”。

例如,bank account 有 state,因为对“我能否 withdraw $100?”这个问题的回答取决于过去的 deposit 和 withdrawal transactions。可以使用一个或多个 state variables 描述 object 的 state;这些 state variables 合起来保存足够的 history information,从而决定 object 的 current behavior。在一个 simple banking system 中,可以用 account 的 current balance 描述它的 state,而不必记住完整的 transaction history。

在由许多 objects 组成的 system 中,objects 很少完全 independent。它们可以通过 interactions 互相影响 state,这些 interactions 把一个 object 的 state variables 与其他 objects 的 state variables coupling 起来。把 system 看作 separate objects 组成的集合,只有在 system 的 state variables 能被分成 tightly coupled、但与其他 subsystems loosely coupled 的 subsystems 时,才特别有用。

这种 view 是组织 system computational models 的 powerful framework。为了使 model modular,应把它分解为模拟 system 中实际 objects 的 computational objects。每个 computational object 都应拥有描述实际 object state 的 local state variables。

由于被 model 的 system 中 objects 的 states 会随时间改变,对应 computational objects 的 state variables 也必须改变。如果选择用 computer 中 elapsed time model system 中的 time,就必须能够构造 behavior 会随着 programs 运行而改变的 computational objects。

特别地,如果希望用 programming language 中的 ordinary symbolic names model state variables,那么 language 必须提供 assignment operator,以改变与 name 关联的 value。

3.1.1 Local State Variables

为了说明 time-varying state 的 computational object,model 从 bank account 中 withdraw money 的 situation。使用一个接收待 withdraw 的 amount 作为 argument 的 procedure withdraw:如果 account 中有足够 money,就返回 withdrawal 后剩余的 balance;否则返回 Insufficient funds。

如果 account 初始有 $100,应该得到:

scheme
(withdraw 25)
75
(withdraw 25)
50
(withdraw 60)
"Insufficient funds"
(withdraw 15)
35

注意,expression (withdraw 25) 被 evaluate 两次却产生不同 values。这是 procedure 的一种 new behavior。此前所有 procedures 都可以看作计算 mathematical functions 的 specification:给定 arguments 的 procedure call 计算 function value,同一 procedure 使用相同 arguments 的两次 calls 总会得到相同 result。1

可以用 variable balance 表示 account balance,并定义访问 balance 的 withdraw procedure:先检查 balance 是否至少等于 requested amount;如果是,就把 balance decrement amount,并返回新的 balance;否则返回 Insufficient funds。

scheme
(define balance 100)

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

Decrement balance 使用 expression:

scheme
(set! balance (- balance amount))

这里使用了 set! special form,其 syntax 是:

scheme
(set! <name> <new-value>)

<name> 是 symbol,<new-value> 是任意 expression。set! 修改 <name>,使它的 value 成为 evaluate <new-value> 所得到的 result。在这里,修改 balance,使它的新 value 等于从旧 balance 中减去 amount 的 result。2

withdraw 还使用 begin special form,使 if test 为 true 时可以 evaluate two expressions:先 decrement balance,再返回 balance value。一般来说,evaluate

scheme
(begin <exp1> <exp2> ... <expk>)

会按 sequence evaluate <exp1> 到 <expk>,并把最后一个 expression <expk> 的 value 作为整个 begin form 的 value。3

虽然 withdraw 能按预期 work,但 variable balance 存在一个问题:如上定义的 balance 是 global environment 中的 name,任何 procedure 都可以 freely access、inspect 或 modify 它。更好的做法是让 balance internal to withdraw,使 withdraw 成为唯一能直接 access balance 的 procedure,其他 procedures 只能通过调用 withdraw 间接 access。这更准确地 model 了 balance 是 withdraw 用来追踪 account state 的 local state variable。

可以重写 definition:

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

这里使用 let 建立一个 environment,其中 local variable balance 绑定到 initial value 100。在这个 local environment 中,用 lambda 创建接收 amount 的 procedure,该 procedure 与之前的 withdraw behavior 相同。

这个 procedure 是 evaluate let expression 后返回的 result,并绑定为 new-withdraw。它的 behavior 与 withdraw 完全相同,但 variable balance 不可被其他 procedures access。4

把 set! 与 local variables 结合,是构造带 local state 的 computational objects 的 general programming technique。

不过,该 technique 引起一个 serious problem:引入 procedures 时,也引入了 substitution model of evaluation,用于解释 procedure application。我们说,apply procedure 应解释为:把 formal parameters 替换成它们的 values 后 evaluate procedure body。

一旦 language 引入 assignment,substitution 就不再是 procedure application 的 adequate model(§3.1.3 会解释原因)。因此,在这一点上,我们实际上还没有办法理解 new-withdraw 为何会按上述方式 behavior。要真正理解 new-withdraw,需要开发一个新的 procedure-application model;§3.2 将介绍这个 model,并解释 set! 和 local variables。现在先考察 new-withdraw 的一些 variations。

下面的 make-withdraw 创建 “withdrawal processors”。make-withdraw 的 formal parameter balance 指定 account 的 initial amount:

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

可以创建两个 objects W1 和 W2:

scheme
(define W1 (make-withdraw 100))
(define W2 (make-withdraw 100))
(W1 50)
50
(W2 70)
30
(W2 40)
"Insufficient funds"
(W1 40)
10

W1 与 W2 是完全 independent 的 objects,每个都拥有自己的 local state variable balance;从一个 object withdraw 不会影响另一个。

还可以创建同时处理 deposits 和 withdrawals 的 objects,从而表示 simple bank accounts:

scheme
(define (make-account balance)
  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount))
               balance)
        "Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (dispatch m)
    (cond ((eq? m 'withdraw) withdraw)
          ((eq? m 'deposit) deposit)
          (else (error "Unknown request -- MAKE-ACCOUNT" m))))
  dispatch)

每次调用 make-account 都建立一个带 local state variable balance 的 environment。在该 environment 中定义 access balance 的 deposit、withdraw procedures,以及接收 “message” 并返回其中一个 local procedure 的 dispatch procedure。dispatch procedure 自身作为代表 bank-account object 的 value 返回。

这正是 §2.4.3 看到的 message-passing style,只是这里把它与修改 local variables 的能力结合起来。

scheme
(define acc (make-account 100))
((acc 'withdraw) 50)
50
((acc 'withdraw) 60)
"Insufficient funds"
((acc 'deposit) 40)
90
((acc 'withdraw) 60)
30

每次调用 acc 都返回 local deposit 或 withdraw procedure,然后将它 apply 到指定的 amount。再调用 make-account:

scheme
(define acc2 (make-account 100))

会产生一个完全 separate 的 account object,它维护自己的 local balance。

Exercises 3.1–3.4

Exercise 3.1. Accumulator 是一个被反复调用、每次接收一个 numeric argument 并把 arguments 累积到 sum 中的 procedure。每次调用都返回当前 accumulated sum。编写生成 accumulators 的 make-accumulator,每个 accumulator 都维护 independent sum,input 指定 sum initial value:

scheme
(define A (make-accumulator 5))
(A 10)
15
(A 10)
25

Exercise 3.2. 在 software testing 中,统计给定 procedure 在一次 computation 中被调用次数很有用。编写 make-monitored,它接收一个自身只接收一个 input 的 procedure f,返回 procedure mf。mf 维护 internal counter;input 为 how-many-calls? 时返回 counter,为 reset-count 时将 counter reset 为 zero;其他 input 则调用 f 并 increment counter。

scheme
(define s (make-monitored sqrt))
(s 100)
10
(s 'how-many-calls?)
1

Exercise 3.3. 修改 make-account,使其创建 password-protected accounts。make-account 额外接收一个 symbol password:

scheme
(define acc (make-account 100 'secret-password))
((acc 'secret-password 'withdraw) 40)
60
((acc 'some-other-password 'deposit) 50)
"Incorrect password"

Account object 只有在 request 携带 creation password 时才处理 request,否则返回 complaint。

Exercise 3.4. 修改 Exercise 3.3 的 make-account,添加另一个 local state variable,使 account 连续七次以上被 incorrect password access 时调用 call-the-cops。

3.1.2 The Benefits of Introducing Assignment

引入 assignment 会带来 difficult conceptual issues,但把 systems 看作拥有 local state 的 objects 集合,是维持 modular design 的 powerful technique。

作为简单 example,考虑 procedure rand:每次调用返回一个 random integer。这里 “chosen at random” 的含义并不 obvious;希望 successive calls 产生具有 uniform-distribution statistical properties 的 number sequence。暂不讨论如何生成 suitable sequence,假设有 rand-update,从给定 $x_1$ 开始:

scheme
x2 = (rand-update x1)
x3 = (rand-update x2)

序列 $x_1,x_2,x_3,ldots$ 具有所需 statistical properties。5

可以用 local state variable x 实现 rand:x 初始化为 fixed random-init,每次调用对 current x 执行 rand-update,返回结果并把它保存为 new x:

scheme
(define rand
  (let ((x random-init))
    (lambda ()
      (set! x (rand-update x))
      x)))

当然,也可以不使用 assignment,直接反复调用 rand-update 生成相同 sequence。但那会要求 program 中每个使用 random numbers 的部分显式记住 current x,并把它作为 argument 传给 rand-update。通过把 state 封装在 rand 内部,assignment 让使用 random-number generator 的 code 更 modular。

Monte Carlo simulation

Monte Carlo methods 是通过 performing experiments、观察实验结果,来估计 difficult-to-compute quantities 的 technique。实验由一组 random choices 决定,每次 experiment 的 result 都是 yes/no。

例如,可以用 number-theoretic experiment 估计 book Z G D 9。随机选择两个 integers,它们 relatively prime 的 probability 是 $6/\pi^2$。因此执行大量 experiments、统计 relatively prime 的 pairs 比例,就可以得到 $6/\pi^2$ 的 estimate,再据此获得 book Z G D 9 的 approximation。

可以使用 monte-carlo:接收 trials 数量和 predicate experiment,反复调用 experiment 并返回 success ratio:

scheme
(define (monte-carlo trials experiment)
  (define (iter trials-remaining trials-passed)
    (cond ((= trials-remaining 0)
           (/ trials-passed trials))
          ((experiment)
           (iter (- trials-remaining 1)
                 (+ trials-passed 1)))
          (else
           (iter (- trials-remaining 1)
                 trials-passed))))
  (iter trials 0))

estimate-pi 使用 rand 的 local state,在每次 trial 中生成 two random integers,并判断它们的 gcd 是否为 1:

scheme
(define (estimate-pi trials)
  (sqrt (/ 6
           (monte-carlo trials cesaro-test))))
(define (cesaro-test)
  (= (gcd (rand) (rand)) 1))

可以把 rand 看作 computational object:它的 local state 保存 sequence 中下一个应使用的 value,调用它的 code 无需显式管理 state。

Exercise 3.5. Monte Carlo integration 是估计 definite integral 的 method。实现 estimate-integral,接收 predicate P、矩形区域的 bounds 和 trials,使用与上面估计 book Z G D 9 相同的 monte-carlo procedure。使用 estimate-integral 通过测量 unit circle 的 area 估计 book Z G D 9。

可以使用以下 random-in-range,它通过 §1.2.6 的 random 返回给定 range 中的 random number:

scheme
(define (random-in-range low high)
  (let ((range (- high low)))
    (+ low (random range))))

Exercise 3.6. 设计可 reset random-number generator 的 new rand procedure。它接收 generate 或 reset:(rand 'generate) 产生 new random number;((rand 'reset) <new-value>) 把 internal state variable reset 为 designated value。Reset state 可以生成 repeatable sequences,这对于 testing 和 debugging 使用 random numbers 的 programs 很有用。

3.1.3 The Costs of Introducing Assignment

set! 能够 model 拥有 local state 的 objects,但代价是 programming language 不再能用 §1.1.5 的 substitution model 解释。实际上,没有带 “nice” mathematical properties 的 simple model,能够充分处理带 objects 和 assignment 的 programming languages。

只要不使用 assignment,同一 procedure 使用相同 arguments 的两次 evaluations 会得到相同 result,因此 procedures 可以看作计算 mathematical functions。像 Chapter 1 和 2 那样完全不使用 assignment 的 programming,称为 functional programming。

为了理解 assignment 如何增加 complexity,考虑不检查 insufficient amount 的 simplified make-withdraw:

scheme
(define (make-simplified-withdraw balance)
  (lambda (amount)
    (set! balance (- balance amount))
    balance))
(define W (make-simplified-withdraw 25))
(W 20)
5
(W 10)
-5

将它与不使用 set! 的 make-decrementer 对比:

scheme
(define (make-decrementer balance)
  (lambda (amount)
    (- balance amount)))
(define D (make-decrementer 25))
(D 20)
5
(D 10)
15

可以用 substitution model 解释 make-decrementer:

scheme
((make-decrementer 25) 20)
((lambda (amount) (- 25 amount)) 20)
(- 25 20)
5

但对 make-simplified-withdraw 做类似 substitution 时:

scheme
((make-simplified-withdraw 25) 20)
((lambda (amount) (set! balance (- 25 amount)) 25) 20)
(set! balance (- 25 20)) 25

如果坚持 substitution model,就必须说 expression 先把 balance set 为 5,再返回 25,这得到错误 answer。为了得到正确 answer,必须区分 set! effect 之前的第一个 balance occurrence 和 effect 之后的第二个 occurrence;substitution model 做不到这一点。

根本问题是:substitution 基于这样的 notion——language 中的 symbols 本质上是 values 的 names。但引入 set! 后,variable 的 value 可以改变,因此 variable 不再只是 name;它必须 refer to 一个可以存放 value 的 place,而该 place 中 stored value 可以改变。§3.2 将展示 environment 如何在 computational model 中扮演这个 “place”。

Sameness and change

这里出现的问题比某个 computation model 的 breakdown 更 profound:一旦在 computational models 中引入 change,许多之前 straightforward 的 notions 都会变得 problematic,包括 “two things being the same”。

调用 make-decrementer 两次并使用相同 argument:

scheme
(define D1 (make-decrementer 25))
(define D2 (make-decrementer 25))

可以接受地回答 D1 和 D2 是 same,因为它们 computational behavior 相同:每个 procedure 都从 25 中减去 input;在任何 computation 中用 D1 替换 D2 都不会改变 result。

但两次调用 make-simplified-withdraw:

scheme
(define W1 (make-simplified-withdraw 25))
(define W2 (make-simplified-withdraw 25))

W1 和 W2 显然不 same:

scheme
(W1 20)
5
(W1 20)
-15
(W2 20)
5

虽然 W1 和 W2 都由 evaluate 同一个 expression (make-simplified-withdraw 25) 创建,但把 W1 替换为 W2 可能改变 expression evaluation result。

如果 language 支持 “equals can be substituted for equals” 而不改变 expression value,就称为 referentially transparent。set! 破坏 referential transparency,因此很难判断何时可用 equivalent expressions 替换来 simplify;对使用 assignment 的 programs 进行 reasoning 会大幅困难。

考虑 Peter 和 Paul 共有一个存有 $100 的 bank account。下面两种 model 有 substantial difference:

scheme
(define peter-acc (make-account 100))
(define paul-acc (make-account 100))

与:

scheme
(define peter-acc (make-account 100))
(define paul-acc peter-acc)

第一种中 accounts distinct,Peter 的 transactions 不影响 Paul;第二种中 paul-acc 与 peter-acc 是 same thing,相当于 joint account,Peter withdrawal 后 Paul 也会观察到更少的 money。

只要不修改 data objects,就可以把 compound data object 看作其 pieces 的 totality;例如 rational number 由 numerator 与 denominator 决定。但有 change 时,compound data object 拥有不同于其 pieces 的 identity:bank account 即使 balance 改变,仍然是 same bank account;也可以有两个拥有相同 state information 的 different bank accounts。

Pitfalls of imperative programming

相对于 functional programming,大量使用 assignment 的 programming 称为 imperative programming。Imperative style 除了使 computational models 更复杂,还容易产生 functional programs 不会出现的 bugs。

例如,可以把 iterative factorial 改写为使用 explicit assignment 更新 product 和 counter:

scheme
(define (factorial n)
  (let ((product 1)
        (counter 1))
    (define (iter)
      (if (> counter n)
          product
          (begin (set! product (* counter product))
                 (set! counter (+ counter 1))
                 (iter))))
    (iter)))

结果与 functional version 相同,但有 subtle trap:assignment 的 order 很重要。下面的相反顺序会产生 different、incorrect result:

scheme
(set! counter (+ counter 1))
(set! product (* counter product))

使用 assignment 的 programming 必须 carefully consider assignments 的 relative order,确保每条 statement 使用的是 changed variables 的正确 version;functional programs 不会遇到这个 issue。

当多个 processes concurrent execute 时,imperative programs 的 complexity 进一步增加;§3.4 将回到这个问题。下一节先建立处理 assignment expressions 的 computational model,并探索带 local state objects 的 simulations。

Exercises 3.1–3.8

Exercise 3.7. 考虑 Exercise 3.3 password modification 后的 make-account bank-account objects。实现 make-joint,创建原始 account 的 additional access。它接收 password-protected account、必须匹配原 password 的 old password,以及 new password:

scheme
(define paul-acc
  (make-joint peter-acc 'open-sesame 'rosebud))

之后可用 paul-acc 和 rosebud password 对 peter-acc transactions。

Exercise 3.8. Evaluation model 说 evaluate expression 的 first step 是 evaluate subexpressions,但没有指定 subexpressions 的 evaluation order(例如 left-to-right 或 right-to-left)。引入 assignment 后,procedure arguments 的 evaluation order 可能改变 result。定义 simple procedure f,使 ( + (f 0) (f 1)) 在 left-to-right 时返回 0,在 right-to-left 时返回 1。

图与格式复核

  • 保留 Monte Carlo 公式中的原始 GIF book-Z-G-D-9.gif,原始尺寸 7×6,并在原文相应位置嵌入。
  • 保留所有 bank-account、random-state、substitution-model 和 imperative-order 的 Scheme code 与 interaction outputs。
  • 本节原文没有独立结构图;除公式 GIF 外,其余 examples 以 code / text 呈现。

术语对照

English中文处理
state / local statestate / local state
state variablestate variable
assignmentassignment
set! / begin保留 Scheme special forms
message passingmessage passing
functional programmingfunctional programming
referential transparencyreferential transparency
imperative programmingimperative programming

参考资料

  1. 在引入 assignment 前也有 exceptions:§1.2.6 的 random-number generator,以及 §2.4.3 的 operation/type tables;相同 arguments 的 get result 可能受 intervening put calls 影响。不过,在引入 assignment 前,无法自行创建这类 procedures。 ↩

  2. set! expression 的 value 是 implementation-dependent;set! 应只为 effect 使用,不应依赖其 value。set! 末尾的 exclamation point 遵循 Scheme naming convention,表示会改变 variables 或 data structures 的 operations;这类似 predicates 使用 question mark 结尾。 ↩

  3. Scheme 中 procedure body 可以是 expression sequence,cond clause 的 consequent 也可以是 sequence,因此之前的 programs 已经 implicitly 使用过 begin。 ↩

  4. let 只是建立 local environment 的便利形式;§3.2 会用 environment model 精确说明 closure 如何保留 balance。 ↩

  5. rand-update sequence 的 quality 取决于具体 random-number algorithm;本节关注 state management,而非 generator 设计。 ↩

← 返回列表
← 上一篇 SICP:2.5 Systems with Generic Operations 下一篇 → SICP:3.2 The Environment Model of Evaluation

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论