Created
March 2, 2016 23:27
-
-
Save erewok/8b264318eb562b8ca8bf to your computer and use it in GitHub Desktop.
Working to implement binary adders in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Adders ( | |
Binary(..) | |
, halfAdder | |
, adder | |
) where | |
import Data.Monoid | |
data Binary = Zero | |
| One | |
deriving (Show, Eq) | |
newtype BinaryNumber = BinaryNumber { runBinary :: [Binary] } | |
type Carry = Binary | |
type Result = Binary | |
instance Monoid Binary where | |
mempty = Zero | |
mappend = andAdd | |
andAdd :: Binary -> Binary -> Carry | |
andAdd Zero Zero = Zero | |
andAdd Zero One = Zero | |
andAdd One Zero = Zero | |
andAdd One One = One | |
orAdd :: Binary -> Binary -> Binary | |
orAdd Zero Zero = Zero | |
orAdd Zero One = One | |
orAdd One Zero = One | |
orAdd One One = One | |
halfAdder :: Binary -> Binary -> Binary | |
halfAdder Zero Zero = Zero | |
halfAdder Zero One = One | |
halfAdder One Zero = One | |
halfAdder One One = Zero | |
adder :: Binary -> Binary -> Carry -> (Result, Carry) | |
adder a b c = (res, car) | |
where res = halfAdder c (halfAdder a b) | |
car = orAdd (a <> b) (halfAdder res c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't remember why I was working on this but I found it in my computer and wanted to save it and come back to it.