-
-
Save jvranish/875490 to your computer and use it in GitHub Desktop.
Simple natural number type
This file contains 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 (Eq, Ord) | |
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 | |
div2 :: Nat -> Nat | |
div2 Zero = Zero | |
div2 (Succ Zero) = Zero | |
div2 (Succ (Succ n)) = Succ (div2 n) | |
main :: IO () | |
main = do | |
let v = take 6 $ map div2 [0..] | |
mapM_ print v | |
{- Output: | |
- | |
- 0 | |
- 0 | |
- 1 | |
- 1 | |
- 2 | |
- 2 | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment