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

SICP:3.3.5 Propagation of Constraints

发布于 2026-09-18 08:47 · 最后编辑于 2026-09-18 10:50 · 版本 v2 · 字数 5,594 · 预计阅读 12 分钟 👁 15 次阅读

SICP:3.3.5 Propagation of Constraints

本文逐段翻译 SICP 第二版 §3.3.5《Propagation of Constraints》,覆盖 constraint networks、connectors、双向 Celsius/Fahrenheit converter、constraint system implementation 与 Exercises 3.33–3.37;保留 Figure 3.28、原始公式图件、Scheme code 与图片尺寸。

TL;DR

  • 普通 program 执行 one-directional computation;constraint system 描述 quantities 之间的 relation,因此同一 network 可以从任意已知 quantity 推导其他 quantity。
  • connector 保存 value、informant 和 associated constraints;constraint 被唤醒后,根据当前 connectors 的 information 推导新的 values。
  • Celsius/Fahrenheit converter 是一个 nondirectional network:设置 C 可以得到 F,清除后设置 F 也可以得到 C。
  • set-value!、forget-value! 和 informant 机制让系统能够检测 contradiction,并撤回由特定 constraint 产生的 values。

目录

章节说明
3.3.5 Propagation of Constraintsconstraint language 与 network
Using the constraint systemCelsius/Fahrenheit converter
Implementing the constraint systemprimitive constraints
Representing connectorsconnector local state
Exercises 3.33–3.37本节练习

3.3.5 Propagation of Constraints

Computer programs traditionally organize one-directional computations:对预先指定的 arguments 执行 operations,以产生 desired outputs。另一方面,我们经常用 quantities 之间的 relations 来 model systems。例如,mechanical structure 的 mathematical model 可能包含如下 information:metal rod 的 deflection d 与 force F、length L、cross-sectional area A 和 elastic modulus E 满足某个 equation:

ch3 Z G 28

这样的 equation 不是 one-directional 的。给定其中任意 four 个 quantities,我们都可以用它计算 fifth quantity。然而,把 equation 翻译成 traditional computer language,会迫使我们选择一个 quantity,规定它由另外 four 个 quantities 计算得到。因此,用来计算 area A 的 procedure 不能被用于计算 deflection d,即使二者的 computations 都来自同一个 equation。

本节概要设计一种能够直接处理 relations 的 language。Language 的 primitive elements 是 primitive constraints,它们声明某些 relations 在 quantities 之间成立。例如,(adder a b c) 指定 a + b = c;(multiplier x y z) 表达 xy = z;(constant 3.14 x) 表达 x 的 value 必须是 3.14。

Language 提供组合 primitive constraints 的方式,以表达更 complex 的 relations。我们构造 constraint networks 来组合 constraints;constraints 由 connectors 连接。Connector 是一个“hold” value 的 object,该 value 可以参与一个或多个 constraints。

例如,Fahrenheit 与 Celsius temperatures 的 relation 是:

ch3 Z G 29

这个 constraint 可以看成由 primitive adder、multiplier 和 constant constraints 构成的 network,如 Figure 3.28 所示。左侧 multiplier 的 m1 terminal 连接到保存 Celsius temperature 的 connector C;m2 连接到 connector w,w 又连接到保存 9 的 constant box;p 连接到另一个 multiplier 的 p。第二个 multiplier 的 m2 连接到 constant 5,m1 连接到 sum 的一个 term。

ch3 Z G 30

Figure 3.28: 把 relation 9C = 5(F - 32) 表达为 constraint network。

Network 的 computation 如下:当 connector 被赋予 value(由 user 或 constraint box 赋予)时,它唤醒所有 associated constraints(刚唤醒它的 constraint 除外),通知它们自己拥有 value。每个被唤醒的 constraint box 检查 connectors,看是否有足够 information 确定某个 connector 的 value。如果有,box 就设置该 connector;connector 随即唤醒所有 associated constraints,如此继续。

在 Celsius/Fahrenheit conversion 中,w、x、y 会被 constant boxes 设置为 9、5、32。如果 user 把 C 设置为 25,最左侧 multiplier 会设置 u = 25 * 9 = 225;u 唤醒第二个 multiplier,将 v 设置为 45;v 再唤醒 adder,将 F 设置为 77。

Using the constraint system

首先创建 connectors C、F,再把它们连接到 network:

scheme
(define C (make-connector))
(define F (make-connector))
(celsius-fahrenheit-converter C F)
ok

Network constructor:

scheme
(define (celsius-fahrenheit-converter c f)
  (let ((u (make-connector))
        (v (make-connector))
        (w (make-connector))
        (x (make-connector))
        (y (make-connector)))
    (multiplier c w u)
    (multiplier v x u)
    (adder v y f)
    (constant 9 w)
    (constant 5 x)
    (constant 32 y)
    'ok))

这个 procedure 创建 internal connectors,并用 adder、multiplier、constant 按 Figure 3.28 连接它们。像 digital-circuit simulator 一样,把 primitive elements 的 combination 表达为 procedures,会为 language 提供 compound objects 的 means of abstraction。

在 C、F 上放置 probes:

scheme
(probe "Celsius temp" C)
(probe "Fahrenheit temp" F)
(set-value! C 25 'user)
Probe: Celsius temp = 25
Probe: Fahrenheit temp = 77
done

如果尝试把已有 value 77 的 F 设置为 212,会得到 contradiction:

scheme
(set-value! F 212 'user)
Error! Contradiction (77 212)

如果要 reuse network,先撤回 C 的 old value:

scheme
(forget-value! C 'user)
Probe: Celsius temp = ?
Probe: Fahrenheit temp = ?
done
(set-value! F 212 'user)
Probe: Fahrenheit temp = 212
Probe: Celsius temp = 100
done

同一个 network 既能根据 C 计算 F,也能根据 F 计算 C。这种 computation 的 nondirectionality,正是 constraint-based systems 的 distinguishing feature。

Implementing the constraint system

Constraint system 通过带 local state 的 procedural objects 实现,方式与 §3.3.4 的 digital-circuit simulator 相似;但 overall system 更简单,因为不需要 agenda 和 logic delays。

Connectors 的 basic operations:

  • (has-value? <connector>):说明 connector 是否有 value。
  • (get-value <connector>):返回 current value。
  • (set-value! <connector> <new-value> <informant>):请求设置 new value。
  • (forget-value! <connector> <retractor>):请求忘记 value。
  • (connect <connector> <new-constraint>):让 connector 参与 new constraint。

Connectors 通过 inform-about-value 与 inform-about-no-value 通知 constraints。

adder 在 a1、a2 与 sum 之间建立 constraint:

scheme
(define (adder a1 a2 sum)
  (define (process-new-value)
    (cond ((and (has-value? a1) (has-value? a2))
           (set-value! sum
                       (+ (get-value a1) (get-value a2))
                       me))
          ((and (has-value? a1) (has-value? sum))
           (set-value! a2
                       (- (get-value sum) (get-value a1))
                       me))
          ((and (has-value? a2) (has-value? sum))
           (set-value! a1
                       (- (get-value sum) (get-value a2))
                       me))))
  (define (process-forget-value)
    (forget-value! sum me)
    (forget-value! a1 me)
    (forget-value! a2 me)
    (process-new-value))
  (define (me request)
    (cond ((eq? request 'I-have-a-value) (process-new-value))
          ((eq? request 'I-lost-my-value) (process-forget-value))
          (else (error "Unknown request -- ADDER" request))))
  (connect a1 me)
  (connect a2 me)
  (connect sum me)
  me)

me 是 adder object 的 dispatch。Syntax interfaces:

scheme
(define (inform-about-value constraint)
  (constraint 'I-have-a-value))
(define (inform-about-no-value constraint)
  (constraint 'I-lost-my-value))

process-new-value 在 adder 获知 connector 有 value 时运行:如果 a1、a2 都有 values,就设置 sum;如果 a1、sum 有 values,就设置 a2;如果 a2、sum 有 values,就设置 a1。当 connector 丢失 value 时,adder 请求其 connectors 丢失由自己设置的 values,然后再次运行 process-new-value,让仍保留的 values 继续传播。

multiplier 类似于 adder,但如果任一 factor 为 0,即使另一个 factor 未知,也会把 product 设置为 0:

scheme
(define (multiplier m1 m2 product)
  (define (process-new-value)
    (cond ((or (and (has-value? m1) (= (get-value m1) 0))
               (and (has-value? m2) (= (get-value m2) 0)))
           (set-value! product 0 me))
          ((and (has-value? m1) (has-value? m2))
           (set-value! product
                       (* (get-value m1) (get-value m2)) me))
          ((and (has-value? product) (has-value? m1))
           (set-value! m2
                       (/ (get-value product) (get-value m1)) me))
          ((and (has-value? product) (has-value? m2))
           (set-value! m1
                       (/ (get-value product) (get-value m2)) me))))
  (define (process-forget-value)
    (forget-value! product me)
    (forget-value! m1 me)
    (forget-value! m2 me)
    (process-new-value))
  (define (me request)
    (cond ((eq? request 'I-have-a-value) (process-new-value))
          ((eq? request 'I-lost-my-value) (process-forget-value))
          (else (error "Unknown request -- MULTIPLIER" request))))
  (connect m1 me)
  (connect m2 me)
  (connect product me)
  me)

constant 只设置 designated connector 的 value;收到其他 request 会报错:

scheme
(define (constant value connector)
  (define (me request)
    (error "Unknown request -- CONSTANT" request))
  (connect connector me)
  (set-value! connector value me)
  me)

probe 在 connector 被 set 或 unset 时打印 message:

scheme
(define (probe name connector)
  (define (print-probe value)
    (newline)
    (display "Probe: ")
    (display name)
    (display " = ")
    (display value))
  (define (process-new-value)
    (print-probe (get-value connector)))
  (define (process-forget-value)
    (print-probe "?"))
  (define (me request)
    (cond ((eq? request 'I-have-a-value) (process-new-value))
          ((eq? request 'I-lost-my-value) (process-forget-value))
          (else (error "Unknown request -- PROBE" request))))
  (connect connector me)
  me)

Representing connectors

Connector 是 procedural object,拥有 local state variables:value、informant(设置 value 的 object)以及 constraints(参与的 constraints list):

scheme
(define (make-connector)
  (let ((value false) (informant false) (constraints '()))
    (define (set-my-value newval setter)
      (cond ((not (has-value? me))
             (set! value newval)
             (set! informant setter)
             (for-each-except setter inform-about-value constraints))
            ((not (= value newval))
             (error "Contradiction" (list value newval)))
            (else 'ignored)))
    (define (forget-my-value retractor)
      (if (eq? retractor informant)
          (begin
            (set! informant false)
            (for-each-except retractor inform-about-no-value constraints))
          'ignored))
    (define (connect new-constraint)
      (if (not (memq new-constraint constraints))
          (set! constraints (cons new-constraint constraints)))
      (if (has-value? me) (inform-about-value new-constraint))
      'done)
    (define (me request)
      (cond ((eq? request 'has-value?) (if informant true false))
            ((eq? request 'value) value)
            ((eq? request 'set-value!) set-my-value)
            ((eq? request 'forget) forget-my-value)
            ((eq? request 'connect) connect)
            (else (error "Unknown operation -- CONNECTOR" request))))
    me))

set-my-value 在 connector 没有 value 时设置 value,并把 setter 记录为 informant,再通知除 setter 外的 constraints。如果已有不同 value,则报告 Contradiction;同一 value 则返回 ignored。forget-my-value 只有在 request 来自当前 informant 时才撤回 value。connect 把 new constraint 加入 list,并在 connector 已有 value 时立即通知它。

scheme
(define (for-each-except exception procedure list)
  (define (loop items)
    (cond ((null? items) 'done)
          ((eq? (car items) exception) (loop (cdr items)))
          (else (procedure (car items))
                (loop (cdr items)))))
  (loop list))

(define (has-value? connector)
  (connector 'has-value?))
(define (get-value connector)
  (connector 'value))
(define (set-value! connector new-value informant)
  ((connector 'set-value!) new-value informant))
(define (forget-value! connector retractor)
  ((connector 'forget) retractor))
(define (connect connector new-constraint)
  ((connector 'connect) new-constraint))

Exercises 3.33–3.37

Exercise 3.33. 使用 primitive multiplier、adder 和 constant constraints,定义 averager。它接收 a、b、c,建立 constraint:c 是 a、b values 的 average。

Exercise 3.34. Louis Reasoner 提议:

scheme
(define (squarer a b)
  (multiplier a a b))

这个 squarer 有 serious flaw。解释为什么:当只有 a 有 value 时,multiplier 把同一个 connector 当成两个 factors;而从 b 反推出 a 时,系统需要从 a*a=b 求 square root,普通 multiplier 并不提供这条 inverse relation。

Exercise 3.35. 把 squarer 定义为 new primitive constraint,补全 Ben Bitdiddle 的 outline:当 b 已知时,负数应报告 square less than 0,否则把 a 设置为 sqrt(b);当 a 已知时,把 b 设置为 a*a;forget 时撤回由 squarer 设置的 values,并重新运行 process-new-value。

scheme
(define (squarer a b)
  (define (process-new-value)
    (cond ((has-value? b)
           (if (< (get-value b) 0)
               (error "square less than 0 -- SQUARER" (get-value b))
               (set-value! a (sqrt (get-value b)) me)))
          ((has-value? a)
           (set-value! b (* (get-value a) (get-value a)) me))))
  (define (process-forget-value)
    (forget-value! a me)
    (forget-value! b me)
    (process-new-value))
  (define (me request)
    (cond ((eq? request 'I-have-a-value) (process-new-value))
          ((eq? request 'I-lost-my-value) (process-forget-value))
          (else (error "Unknown request -- SQUARER" request))))
  (connect a me)
  (connect b me)
  me)

Exercise 3.36. 在 global environment 中依次求值:

scheme
(define a (make-connector))
(define b (make-connector))
(set-value! a 10 'user)

当 set-value! 正在执行 connector 的 local procedure 中的 (for-each-except setter inform-about-value constraints) 时,画出该 expression 所在 environment 的 environment diagram。

Exercise 3.37. 定义 constraint versions 的 arithmetic operations,使 converter 可以采用 expression-oriented style:

scheme
(define (celsius-fahrenheit-converter x)
  (c+ (c* (c/ (cv 9) (cv 5)) x)
      (cv 32)))
(define C (make-connector))
(define F (celsius-fahrenheit-converter C))

例如 c+:

scheme
(define (c+ x y)
  (let ((z (make-connector)))
    (adder x y z)
    z))

定义 analogous 的 c-、c*、c/ 和 cv(constant value),让 compound constraints 可以像 converter example 一样组合。

图与格式复核

  • 保留 Figure 3.28 以及两个原始公式图件,位置与原文对应。
  • 图片显示宽度按原始 pixel width 保留:67、95、357。
  • 保留 converter、adder、multiplier、constant、probe、connector 和 exercises 的 Scheme code。

术语对照

English中文处理
constraint / relationconstraint / relation
connectorconnector
constraint networkconstraint network
informant / retractorinformant / retractor
propagationpropagation
contradictioncontradiction
nondirectional computationnondirectional computation

参考资料

← 返回列表
← 上一篇 SICP:3.3.4 A Simulator for Digital Circuits 下一篇 → SICP:3.4 Concurrency: Time Is of the Essence

评论 (0)

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