Created
March 17, 2011 21:36
-
-
Save sw17ch/875187 to your computer and use it in GitHub Desktop.
Division by two
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
-- div2.hs | |
data Nat = Zero | Succ Nat | |
deriving (Show) | |
zero = Zero | |
one = Succ zero | |
two = Succ one | |
three = Succ two | |
four = Succ three | |
five = Succ four | |
div2 :: Nat -> Nat | |
div2 Zero = Zero | |
div2 (Succ Zero) = Zero | |
div2 (Succ (Succ n)) = Succ (div2 n) | |
main :: IO () | |
main = do | |
let v = map div2 [zero, one, two, three, four, five] | |
mapM_ print v | |
{- Output: | |
- | |
- Zero | |
- Zero | |
- Succ Zero | |
- Succ Zero | |
- Succ (Succ Zero) | |
- Succ (Succ Zero) | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
instance Show Nat where
show a = show $ fromEnum a
instance Num Nat where
a + Succ b = Succ a + b
a + Zero = a
Succ a - Succ b = a - b
a - Zero = a
Zero - _ = Zero
fromInteger n = (iterate Succ Zero) !! (fromInteger n)
instance Enum Nat where
succ a = Succ a
pred (Succ a) = a
toEnum n = fromInteger $ toInteger n
fromEnum Zero = 0
fromEnum (Succ a) = 1 + fromEnum a