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