Add a duplication 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 -- Not really an adder either, but a slightly more complex example
22 invinv :: Bit -> Bit
23 invinv a = hwnot (hwnot a)
24
25 -- Not really an adder either, but a slightly more complex example
26 dup :: Bit -> (Bit, Bit)
27 dup a = (a, a)
28
29 -- Combinatoric stateless no-carry adder
30 -- A -> B -> S
31 no_carry_adder :: (Bit, Bit) -> Bit
32 no_carry_adder (a, b) = a `hwxor` b
33
34 -- Combinatoric stateless half adder
35 -- A -> B -> (S, C)
36 half_adder :: (Bit, Bit) -> (Bit, Bit)
37 half_adder (a, b) = 
38   ( a `hwxor` b, a `hwand` b )
39
40 -- Combinatoric stateless full adder
41 -- (A, B, C) -> (S, C)
42 full_adder :: (Bit, Bit, Bit) -> (Bit, Bit)
43 full_adder (a, b, cin) = (s, c)
44   where
45     s = a `hwxor` b `hwxor` cin
46     c = a `hwand` b `hwor` (cin `hwand` (a `hwxor` b))
47
48 -- Four bit adder
49 -- Explicit version
50 -- [a] -> [b] -> ([s], cout)
51 exp_adder :: ([Bit], [Bit]) -> ([Bit], Bit)
52
53 exp_adder ([a3,a2,a1,a0], [b3,b2,b1,b0]) =
54   ([s3, s2, s1, s0], c3)
55   where
56     (s0, c0) = full_adder (a0, b0, Low)
57     (s1, c1) = full_adder (a1, b1, c0)
58     (s2, c2) = full_adder (a2, b2, c1)
59     (s3, c3) = full_adder (a3, b3, c2)
60
61 -- Any number of bits adder
62 -- Recursive version
63 -- [a] -> [b] -> ([s], cout)
64 rec_adder :: ([Bit], [Bit]) -> ([Bit], Bit)
65
66 rec_adder ([], []) = ([], Low)
67 rec_adder ((a:as), (b:bs)) = 
68   (s : rest, cout)
69   where
70     (rest, cin) = rec_adder (as, bs)
71     (s, cout) = full_adder (a, b, cin)
72
73 -- Four bit adder, using the continous adder below
74 -- [a] -> [b] -> ([s], cout)
75 --con_adder_4 as bs = 
76 --  ([s3, s2, s1, s0], c)
77 --  where
78 --    ((s0, _):(s1, _):(s2, _):(s3, c):_) = con_adder (zip ((reverse as) ++ lows) ((reverse bs) ++ lows))
79
80 -- Continuous sequential version
81 -- Stream a -> Stream b -> Stream (sum, cout)
82 --con_adder :: Stream (Bit, Bit) -> Stream (Bit, Bit)
83
84 -- Forward to con_adder_int, but supply an initial state
85 --con_adder pin =
86 --  con_adder_int pin Low
87
88 -- Stream a -> Stream b -> state -> Stream (s, c)
89 --con_adder_int :: Stream (Bit, Bit) -> Bit -> Stream (Bit, Bit)
90 --con_adder_int ((a,b):rest) cin =
91 --  (s, cout) : con_adder_int rest cout
92 --  where
93 --    (s, cout) = full_adder a b cin
94
95 -- vim: set ts=8 sw=2 sts=2 expandtab: