Skip to content

Instantly share code, notes, and snippets.

@jvranish
Forked from sw17ch/div2.hs
Created March 18, 2011 01:49
Show Gist options
  • Save jvranish/875490 to your computer and use it in GitHub Desktop.
Save jvranish/875490 to your computer and use it in GitHub Desktop.
Simple natural number type
-- 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