Add an invertor hardware model.
[matthijs/master-project/cλash.git] / Adders.hs
1 module Adders where
2 import Bits
3 import Language.Haskell.Syntax
4
5 main = do show_add exp_adder; show_add rec_adder;
6
7 show_add f = do print ("Sum:   " ++ (displaysigs s)); print ("Carry: " ++ (displaysig c))
8   where
9     a = [High, High, High, High]
10     b = [Low, Low, Low, High]
11     (s, c) = f (a, b)
12
13 -- Not really an adder, but this is nice minimal hardware description
14 wire :: Bit -> Bit
15 wire a = a
16
17 -- Not really an adder either, but a slightly more complex example
18 inv :: Bit -> Bit
19 inv a = hwnot a
20
21 -- Combinatoric stateless no-carry adder
22 -- A -> B -> S
23 no_carry_adder :: (Bit, Bit) -> Bit
24 no_carry_adder (a, b) = a `hwxor` b
25
26 -- Combinatoric stateless half adder
27 -- A -> B -> (S, C)
28 half_adder :: (Bit, Bit) -> (Bit, Bit)
29 half_adder (a, b) = 
30   ( a `hwxor` b, a `hwand` b )
31
32 -- Combinatoric stateless full adder
33 -- (A, B, C) -> (S, C)
34 full_adder :: (Bit, Bit, Bit) -> (Bit, Bit)
35 full_adder (a, b, cin) = (s, c)
36   where
37     s = a `hwxor` b `hwxor` cin
38     c = a `hwand` b `hwor` (cin `hwand` (a `hwxor` b))
39
40 -- Four bit adder
41 -- Explicit version
42 -- [a] -> [b] -> ([s], cout)
43 exp_adder :: ([Bit], [Bit]) -> ([Bit], Bit)
44
45 exp_adder ([a3,a2,a1,a0], [b3,b2,b1,b0]) =
46   ([s3, s2, s1, s0], c3)
47   where
48     (s0, c0) = full_adder (a0, b0, Low)
49     (s1, c1) = full_adder (a1, b1, c0)
50     (s2, c2) = full_adder (a2, b2, c1)
51     (s3, c3) = full_adder (a3, b3, c2)
52
53 -- Any number of bits adder
54 -- Recursive version
55 -- [a] -> [b] -> ([s], cout)
56 rec_adder :: ([Bit], [Bit]) -> ([Bit], Bit)
57
58 rec_adder ([], []) = ([], Low)
59 rec_adder ((a:as), (b:bs)) = 
60   (s : rest, cout)
61   where
62     (rest, cin) = rec_adder (as, bs)
63     (s, cout) = full_adder (a, b, cin)
64
65 -- Four bit adder, using the continous adder below
66 -- [a] -> [b] -> ([s], cout)
67 --con_adder_4 as bs = 
68 --  ([s3, s2, s1, s0], c)
69 --  where
70 --    ((s0, _):(s1, _):(s2, _):(s3, c):_) = con_adder (zip ((reverse as) ++ lows) ((reverse bs) ++ lows))
71
72 -- Continuous sequential version
73 -- Stream a -> Stream b -> Stream (sum, cout)
74 --con_adder :: Stream (Bit, Bit) -> Stream (Bit, Bit)
75
76 -- Forward to con_adder_int, but supply an initial state
77 --con_adder pin =
78 --  con_adder_int pin Low
79
80 -- Stream a -> Stream b -> state -> Stream (s, c)
81 --con_adder_int :: Stream (Bit, Bit) -> Bit -> Stream (Bit, Bit)
82 --con_adder_int ((a,b):rest) cin =
83 --  (s, cout) : con_adder_int rest cout
84 --  where
85 --    (s, cout) = full_adder a b cin
86
87 -- vim: set ts=8 sw=2 sts=2 expandtab: