(load-option 'hash-table) (define make-table make-eq-hash-table) (define table-get hash-table/get) (define table-put! hash-table/put!) (define table-data hash-table/datum-list) (define table-clear! hash-table/clear!) (define (lookup inputs lookup-table) (second (assoc inputs lookup-table))) (define and-table '(((#t #t) #t) ((#t #f) #f) ((#f #t) #f) ((#f #f) #f))) (define or-table '(((#t #t) #t) ((#t #f) #t) ((#f #t) #t) ((#f #f) #f))) (define nand-table '(((#t #t) #f) ((#t #f) #t) ((#f #t) #t) ((#f #f) #t))) (define not-table '(((#f) #t) ((#t) #f))) (define (make-component name table inputs) (list 'component name table inputs)) (define (component-name component) (second component)) (define (component-table component) (third component)) (define (component-inputs component) (fourth component)) (define (component? x) (and (pair? x) (eq? (car x) 'component))) ; component table abstraction (define table-of-components (make-table)) (define (add-component! name table inputs) (table-put! table-of-components name (make-component name table inputs))) (define (all-components) (table-data table-of-components)) ; output table abstraction (define output-table (make-table)) (define (set-output! name value) (table-put! output-table name value)) (define (get-output name) (table-get output-table name 'not-ready)) (define (clear-output!) (table-clear! output-table)) ; component processing procedures (define (component-output-data component data) (set-output! (component-name component) data)) (define (component-process component) (let ((inputs (map get-output (component-inputs component)))) (if (memq 'not-ready inputs) 'nothing-to-process (component-output-data component (lookup inputs (component-table component)))))) ; simulation code (define (step output) (if (eq? (get-output output) 'not-ready) (begin (map component-process (all-components)) (step output)) (get-output output))) (define (simulate inputs output) (clear-output!) (map (lambda (input) (set-output! (car input) (cadr input))) inputs) (step output)) ; example (add-component! 'D not-table '(A)) (add-component! 'E and-table '(B D)) (add-component! 'F or-table '(C E)) (simulate '((A #f) (B #t) (C #f)) 'F) ;(define (make-table) ; (list 'atable)) ;(define (table-put! table key value) ; (set-cdr! table (cons (list key value) (cdr table)))) ;(define (table-clear! table) ; (set-cdr! table nil)) ;(define (table-get table key default-value) ; (let ((val (assq key (cdr table)))) ; (if val ; (cadr val) ; default-value))) ;(define (table-data table) ; (map cadr (cdr table)))