乐正

Actions speak louder than words.

Sicp-ex3-35

问题

Ben Bididdle 告诉 Louis,为了避免他在练习3.34中遇到的麻烦,一种方式是将平方器定义为一个新的基本约束。请填充 Ben 所给出的下面过程概要,实现这样的约束:

1
2
3
4
5
6
7
8
9
10
11
(define (squarer a b)
  (define (process-new-value)
    (if (has-value? b)
      (if (< (get-value b) 0)
          (error "square less than 0")))))
          <alternative>
      <alternative>
  (define (process-forget-value) <body1>)
  (define (me request) <body2>)
  <其他定义>
  me)

解答

练习3.35 (ex3-35.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(define (squarer a b)
  (define (process-new-value)
    (if (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)))
    (if (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)

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
(define a (make-connector))
(define b (make-connector))

(squarer a b)
$6 = #<procedure me (request)>

(probe "Squarer a: " a)
$7 = #<procedure me (request)>

(probe "Squarer b: " b)
$8 = #<procedure me (request)>

(set-value! a 10 'user)
Probe: Squarer a:  = 10
Probe: Squarer b:  = 100
$9 = done

(forget-value! a 'user)
Probe: Squarer a:  = ?
Probe: Squarer b:  = ?
$10 = done

(set-value! b 9 'user)
Probe: Squarer b:  = 9
Probe: Squarer a:  = 3
$11 = done

draft

« sicp-ex3-34 sicp-ex3-36 »

Comments