1 module Adders (main, no_carry_adder) where
3 import Language.Haskell.Syntax
5 main = do show_add exp_adder; show_add rec_adder;
7 show_add f = do print ("Sum: " ++ (displaysigs s)); print ("Carry: " ++ (displaysig c))
9 a = [High, High, High, High]
10 b = [Low, Low, Low, High]
13 -- Combinatoric no-carry adder
15 no_carry_adder :: (Bit, Bit) -> Bit
16 no_carry_adder (a, b) = a `hwxor` b
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)
23 s = a `hwxor` b `hwxor` cin
24 c = a `hwand` b `hwor` (cin `hwand` (a `hwxor` b))
28 -- [a] -> [b] -> ([s], cout)
29 exp_adder :: ([Bit], [Bit]) -> ([Bit], Bit)
31 exp_adder ([a3,a2,a1,a0], [b3,b2,b1,b0]) =
32 ([s3, s2, s1, s0], c3)
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)
39 -- Any number of bits adder
41 -- [a] -> [b] -> ([s], cout)
42 rec_adder :: ([Bit], [Bit]) -> ([Bit], Bit)
44 rec_adder ([], []) = ([], Low)
45 rec_adder ((a:as), (b:bs)) =
48 (rest, cin) = rec_adder (as, bs)
49 (s, cout) = full_adder (a, b, cin)
51 -- Four bit adder, using the continous adder below
52 -- [a] -> [b] -> ([s], cout)
54 -- ([s3, s2, s1, s0], c)
56 -- ((s0, _):(s1, _):(s2, _):(s3, c):_) = con_adder (zip ((reverse as) ++ lows) ((reverse bs) ++ lows))
58 -- Continuous sequential version
59 -- Stream a -> Stream b -> Stream (sum, cout)
60 --con_adder :: Stream (Bit, Bit) -> Stream (Bit, Bit)
62 -- Forward to con_adder_int, but supply an initial state
64 -- con_adder_int pin Low
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
71 -- (s, cout) = full_adder a b cin
73 -- vim: set ts=8 sw=2 sts=2 expandtab: