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