Files
sicp-exercises/sec-3-3-4.scm

53 lines
1.4 KiB
Scheme

;; The digital circuit program is very interesting,
;; not just because it is a good demonstration of scheme,
;; but also because I really think this is a practical
;; program.
;; anyway, here are the exercises
;; so, the book does not provide an implementation for make-wire,
;; get-signal, set-signal!, add-action! and after-delay
;; so if we want this code to run, we need to implement them.
;; I chose to use a closure for this, because this is something
;; I really learned with SICP so may as well. We could also use
;; a box (in r6rs I believe, or at least chez)
;; and in all fairness I believe that is more efficient, however this was funny
;; EDIT: later on in the chapter the book actually provides a similar implementation
;; so I guess I'm prescient now
(define (make-wire)
(let ((val #f) (actions '()))
(lambda (x param)
(cond
((eq? x 'get) val)
((eq? x 'set!)
(if (not (boolean=? val param))
(begin (set! val param)
(map (lambda (x) (x))
actions))))
((eq? x 'add-action!)
(set! actions (cons param actions))
(param))))))
(define (get-signal w)
(w 'get 'USELESS))
(define (set-signal! w val)
(w 'set! val))
(define (add-action! w action)
(w 'add-action! action))
(define a (make-wire))
(define b (make-wire))
(define c (make-wire))
(define d (make-wire))
(define e (make-wire))
(define s (make-wire))