module TFwH.Chap03.ExG where
import Prelude hiding (divMod)
data Nat = Zero | Succ Nat deriving (Eq, Show)
instance Ord Nat where
Zero <= Zero = True
Zero <= Succ n = True
Succ m <= Zero = False
Succ m <= Succ n = m <= n
instance Num Nat where
m + Zero = m
m + Succ n = Succ (m + n)
m * Zero = Zero
m * Succ n = m * n + m
abs n = n
signum Zero = Zero
signum (Succ n) = Succ Zero
m - Zero = m
Zero - Succ n = Zero
Succ m - Succ n = m - n
fromInteger x
| x <= 0 = Zero
| otherwise = Succ (fromInteger (x - 1))
divMod :: Nat -> Nat -> (Nat, Nat)
divMod x y = if x < y then (Zero, x)
else (Succ q, r)
where
(q, r) = divMod (x - y) y