; Logic implementation of a mod-3 adder in Scheme ; Only logic functions are used, except for testing. (load "tester.scm") ; (encode d) encodes a number in {0, 1, 2} into a list of truth values (define (encode d) (case d ('0 '(#f #f)) ('1 '(#f #t)) ('2 '(#t #f)) (else (error "undefined encode" d)))) ; (decode e) encodes a list of truth values into a number {0, 1, 2} (define (decode e) (cond ((equal? e '(#f #f)) 0) ((equal? e '(#f #t)) 1) ((equal? e '(#t #f)) 2) (else ((error "undefined decode" e))))) ; add3 is the function we are implementing ; This version is jus used for testing. (define (add3 i j) (modulo (+ i j) 3)) ; addByCircuit is for testing. It encodes the arguments, ; adds the encoded values, producing a third encoded value, ; then decodes that. (define (addByCircuit i j) (decode (circuit (encode i) (encode j)))) ; circuit operates on encoded values to produce an ; encoded value of the mod-3 sum. It is based on the ; minterm expansion of two logic functions. (define (circuit y z) (let ((u (first y)) (v (second y)) (w (first z)) (x (second z))) (list (or ; The first bit of the result (and (not u) (not v) w (not x)) (and (not u) v (not w) x) (and u (not v) (not w) (not x))) (or ; The second bit of the result (and (not u) (not v) (not w) x) (and (not u) v (not w) (not x)) (and u (not v) w (not x)))))) ; Exhaustive test (test (addByCircuit 0 0) (add3 0 0)) (test (addByCircuit 0 1) (add3 0 1)) (test (addByCircuit 0 2) (add3 0 2)) (test (addByCircuit 1 0) (add3 1 0)) (test (addByCircuit 1 1) (add3 1 1)) (test (addByCircuit 1 2) (add3 1 2)) (test (addByCircuit 2 0) (add3 2 0)) (test (addByCircuit 2 1) (add3 2 1)) (test (addByCircuit 2 2) (add3 2 2)) (tester 'show)