Skip to content

Commit 3261b0f

Browse files
committed
Add implementation and test for half-adder and full-adder
1 parent 6c5912b commit 3261b0f

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

chapter3/adder.rkt

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#lang racket
2+
(require "digital-circuit.rkt")
3+
(require "after-delay.rkt")
4+
5+
(define (half-adder a b s c)
6+
(let ((d (make-wire))
7+
(e (make-wire)))
8+
(or-gate a b d)
9+
(and-gate a b c)
10+
(inverter c e)
11+
(and-gate d e s))
12+
'ok)
13+
14+
(define (full-adder a b c-in sum c-out)
15+
(let ((s (make-wire))
16+
(c1 (make-wire))
17+
(c2 (make-wire)))
18+
(half-adder b c-in s c1)
19+
(half-adder a s sum c2)
20+
(or-gate c1 c2 c-out))
21+
'ok)
22+
23+
(module+ test
24+
(require rackunit)
25+
26+
(test-case "Test for half-adder"
27+
(define a (make-wire))
28+
(define b (make-wire))
29+
(define s (make-wire))
30+
(define c (make-wire))
31+
;; A B Sum (S) Carry (C)
32+
;; 0 0 0 0
33+
;; 0 1 1 0
34+
;; 1 0 1 0
35+
;; 1 1 0 1
36+
(half-adder a b s c)
37+
(propagate)
38+
(check-equal? (get-signal s) 0)
39+
(check-equal? (get-signal c) 0)
40+
41+
(set-signal! b 1)
42+
(propagate)
43+
(check-equal? (get-signal s) 1)
44+
(check-equal? (get-signal c) 0)
45+
46+
(set-signal! b 0)
47+
(set-signal! a 1)
48+
(propagate)
49+
(check-equal? (get-signal s) 1)
50+
(check-equal? (get-signal c) 0)
51+
52+
(set-signal! b 1)
53+
(propagate)
54+
(check-equal? (get-signal s) 0)
55+
(check-equal? (get-signal c) 1)
56+
)
57+
58+
(test-case "Test-for full-adder"
59+
;; A B Cin S Cout
60+
;; 0 0 0 0 0
61+
;; 0 0 1 1 0
62+
;; 0 1 0 1 0
63+
;; 0 1 1 0 1
64+
;; 1 0 0 1 0
65+
;; 1 0 1 0 1
66+
;; 1 1 0 0 1
67+
;; 1 1 1 1 1
68+
(define a (make-wire))
69+
(define b (make-wire))
70+
(define c-in (make-wire))
71+
(define s (make-wire))
72+
(define c-out (make-wire))
73+
(full-adder a b c-in s c-out)
74+
75+
(propagate)
76+
(check-equal? (get-signal s) 0)
77+
(check-equal? (get-signal c-out) 0)
78+
79+
(set-signal! b 1)
80+
(set-signal! c-in 1)
81+
(propagate)
82+
(check-equal? (get-signal s) 0)
83+
(check-equal? (get-signal c-out) 1)
84+
85+
(set-signal! a 1)
86+
(propagate)
87+
(check-equal? (get-signal s) 1)
88+
(check-equal? (get-signal c-out) 1)
89+
)
90+
)

0 commit comments

Comments
 (0)