Skip to content

Instantly share code, notes, and snippets.

@dmwit
Created July 9, 2020 15:14
Show Gist options
  • Save dmwit/2b13d2d47b8ec6cef4beabe3cac36224 to your computer and use it in GitHub Desktop.
Save dmwit/2b13d2d47b8ec6cef4beabe3cac36224 to your computer and use it in GitHub Desktop.
data Nat = Zero | Succ Nat | Twice Nat Nat deriving (Eq, Ord, Read, Show)
half :: Nat -> Nat
half Zero = Zero
half (Succ n) = half n
half (Twice _ n) = n
-- pred
p :: Nat -> Nat
p Zero = Zero
p (Succ n) = n
p (Twice n _) = n
-- succ
s :: Nat -> Nat
s (Succ n) = twice (s (half n))
s n = Succ n
twice :: Nat -> Nat
twice Zero = Zero
twice n = Twice (s (twice (p n))) n
-- fromInteger
fi :: Integer -> Nat
fi 0 = Zero
fi n = case n `quotRem` 2 of
(q, r) -> (if r == 0 then id else s) (twice (fi q))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment