-- Peano numbers -------------------------------------------------------------- data Pe = Zero -- 0 | S Pe -- Pe + 1 deriving (Show) -- basic arithmetic operations ------------------------------------------------ add :: Pe -> Pe -> Pe add Zero y = y -- 0 + y = y add (S x) y = S (add x y) -- (x + 1) + y = (x + y) + 1 mul :: Pe -> Pe -> Pe mul Zero y = Zero -- 0 * y = 0 mul (S x) y = add (mul x y) y -- (x + 1) * y = (x * y) + y sub :: Pe -> Pe -> Pe sub Zero y = Zero -- 0 - y = 0 sub x Zero = x -- x - 0 = x sub (S x) (S y) = sub x y -- (x + 1) - (y + 1) = x - y -- input/output --------------------------------------------------------------- toInt :: Pe -> Int toInt Zero = 0 toInt (S x) = 1 + toInt x toPe :: Int -> Pe toPe 0 = Zero toPe x = S (toPe (x - 1)) -- ---------------------------------------------------------------------------- main = do let zero = Zero let one = S(Zero) let two = S(S(Zero)) print $ (show . toInt $ zero) ++ " := " ++ (show zero) print $ (show . toInt $ one) ++ " := " ++ (show one) print $ (show . toInt $ two) ++ " := " ++ (show two) print $ "3 := " ++ (show $ S(S(S(Zero)))) print $ "4 := " ++ (show $ add two two) print $ "5 := " ++ (show $ add (mul two two) one) print $ "6 := " ++ (show $ toPe (3 + 3)) print $ "7 := " ++ (show $ sub (mul (mul two two) two) one) print $ "8 := " ++ (show $ mul (mul two two) two) print $ "9 := " ++ (show $ toPe (3 * 3))