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