shithub: MicroHs

Download patch

ref: f7236224b0e0d091ab0bd9f40017e527b96f87a3
parent: ac32433bdf0e873146e629eb5d126b1798c6bfc8
author: Lennart Augustsson <lennart@augustsson.net>
date: Wed Apr 3 05:16:57 EDT 2024

Add Numeric.Natural

--- a/lib/AllOfLib.hs
+++ b/lib/AllOfLib.hs
@@ -80,6 +80,7 @@
 import GHC.Stack
 import GHC.Types
 import Numeric
+import Numeric.Natural
 import Prelude
 import Primitives
 import System.Console.SimpleReadline
--- /dev/null
+++ b/lib/Numeric/Natural.hs
@@ -1,0 +1,35 @@
+module Numeric.Natural
+  ( Natural
+  , minusNaturalMaybe
+  ) where
+import Control.Exception
+
+newtype Natural = N Integer
+  deriving (Eq, Ord)
+
+instance Show Natural where
+  showsPrec p (N i) = showsPrec p i
+
+instance Num Natural where
+  N x + N y = N (x + y)
+  N x - N y | y > x = throw Underflow
+  N x * N y = N (x * y)
+  abs x = x
+  signum x = if x > 0 then 1 else 0
+  fromInteger x | x < 0 = throw Underflow
+                | otherwise = N x
+
+instance Enum Natural where
+  toEnum   = fromInteger . toInteger
+  fromEnum = fromInteger . toInteger
+
+instance Integral Natural where
+  toInteger (N i) = i
+  quotRem (N x) (N y) = (N q, N r) where (q, r) = quotRem x y
+
+instance Real Natural where
+  toRational (N i) = toRational i
+
+minusNaturalMaybe :: Natural -> Natural -> Maybe Natural
+minusNaturalMaybe x y | x < y = Nothing
+                      | otherwise = Just (x - y)
--