|
| 1 | +#lang racket |
| 2 | +(require "constraints.rkt") |
| 3 | + |
| 4 | +(define (squarer a b) |
| 5 | + (define (process-new-value) |
| 6 | + ;; 原书的实现有缺陷,它假定 b 有值的时候 a 没有值,a 有值的时候 b |
| 7 | + ;; 没有, 但是也存在一种可能是 a 和 b 都没有值, 比如在调用 |
| 8 | + ;; =(process-forget-value)= 时 |
| 9 | + (cond ((and (has-value? a) (not (has-value? b))) |
| 10 | + (set-value! b (* (get-value a) (get-value a)) |
| 11 | + me)) |
| 12 | + ((and (has-value? b) (not (has-value? a))) |
| 13 | + (if (< (get-value b) 0) |
| 14 | + (error "square less than 0 -- SQUARER" (get-value b)) |
| 15 | + ;; 还有一种可能就是有 (- (sqrt b) |
| 16 | + (set-value! a (sqrt (get-value b)) |
| 17 | + me))))) |
| 18 | + |
| 19 | + (define (process-forget-value) |
| 20 | + (forget-value! a me) |
| 21 | + (forget-value! b me) |
| 22 | + (process-new-value)) |
| 23 | + |
| 24 | + (define (me request) |
| 25 | + (cond ((eq? request 'I-have-a-value) |
| 26 | + (process-new-value)) |
| 27 | + |
| 28 | + ((eq? request 'I-lost-my-value) |
| 29 | + (process-forget-value)) |
| 30 | + |
| 31 | + (else |
| 32 | + (error "Unknown request -- MULTIPLIER" request)))) |
| 33 | + |
| 34 | + (connect a me) |
| 35 | + (connect b me) |
| 36 | + me) |
| 37 | + |
| 38 | +(module+ test |
| 39 | + (require rackunit) |
| 40 | + |
| 41 | + (test-case "Test for squarer with a set" |
| 42 | + (define a (make-connector)) |
| 43 | + (define b (make-connector)) |
| 44 | + (squarer a b) |
| 45 | + (probe "value a" a) |
| 46 | + (probe "value b" b) |
| 47 | + (check-false (has-value? a)) |
| 48 | + (check-false (has-value? b)) |
| 49 | + (set-value! a 5 'user) |
| 50 | + (check-equal? (get-value b) 25) |
| 51 | + |
| 52 | + (forget-value! a 'user) |
| 53 | + (check-false (has-value? a)) |
| 54 | + (set-value! a -5 'user) |
| 55 | + (check-equal? (get-value b) 25) |
| 56 | + ) |
| 57 | + |
| 58 | + (test-case "Test for squarer with b set" |
| 59 | + (define a (make-connector)) |
| 60 | + (define b (make-connector)) |
| 61 | + (squarer a b) |
| 62 | + (probe "value a" a) |
| 63 | + (probe "value b" b) |
| 64 | + (check-false (has-value? a)) |
| 65 | + (check-false (has-value? b)) |
| 66 | + (set-value! b 25 'user) |
| 67 | + (check-equal? (get-value a) 5) |
| 68 | + |
| 69 | + (forget-value! b 'user) |
| 70 | + (check-false (has-value? a)) |
| 71 | + (set-value! b 16 'user) |
| 72 | + (check-equal? (get-value a) 4) |
| 73 | + ) |
| 74 | + ) |
0 commit comments