Skip to content

Instantly share code, notes, and snippets.

@erewok
Created March 2, 2016 23:27
Show Gist options
  • Save erewok/8b264318eb562b8ca8bf to your computer and use it in GitHub Desktop.
Save erewok/8b264318eb562b8ca8bf to your computer and use it in GitHub Desktop.
Working to implement binary adders in Haskell
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)
@erewok
Copy link
Author

erewok commented Mar 2, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment