summaryrefslogtreecommitdiff
path: root/libraries/base/GHC/Natural.hs
diff options
context:
space:
mode:
authorHerbert Valerio Riedel <hvr@gnu.org>2014-11-22 14:52:04 +0100
committerHerbert Valerio Riedel <hvr@gnu.org>2014-11-22 15:14:02 +0100
commit4b6537677fa9460ca5febe2eb79a2d9d5bdadba2 (patch)
tree5f4bde961790a80c0fd915b87ced8816fed82fde /libraries/base/GHC/Natural.hs
parent5ea3ee02c7e616235508f1829f8ccfd6047eaf98 (diff)
downloadhaskell-4b6537677fa9460ca5febe2eb79a2d9d5bdadba2.tar.gz
Add `isValidNatural` predicate (#9818)
This predicate function encodes the internal `Natural` invariants, and is useful for testsuites or code that directly constructs `Natural` values. C.f. `integer-gmp2`'s `isValidBigNat#` and `isValidInteger#` predicates for testing internal invariants.
Diffstat (limited to 'libraries/base/GHC/Natural.hs')
-rw-r--r--libraries/base/GHC/Natural.hs21
1 files changed, 21 insertions, 0 deletions
diff --git a/libraries/base/GHC/Natural.hs b/libraries/base/GHC/Natural.hs
index 7c362ace56..0dead29e64 100644
--- a/libraries/base/GHC/Natural.hs
+++ b/libraries/base/GHC/Natural.hs
@@ -35,6 +35,7 @@ module GHC.Natural
-- (i.e. which constructors are available) depends on the
-- 'Integer' backend used!
Natural(..)
+ , isValidNatural
-- * Conversions
, wordToNatural
, naturalToWordMaybe
@@ -87,6 +88,17 @@ data Natural = NatS# GmpLimb# -- ^ in @[0, maxBound::Word]@
deriving (Eq,Ord) -- NB: Order of constructors *must*
-- coincide with 'Ord' relation
+-- | Test whether all internal invariants are satisfied by 'Natural' value
+--
+-- This operation is mostly useful for test-suites and/or code which
+-- constructs 'Integer' values directly.
+--
+-- /Since: 4.8.0.0/
+isValidNatural :: Natural -> Bool
+isValidNatural (NatS# _) = True
+isValidNatural (NatJ# bn) = isTrue# (isValidBigNat# bn)
+ && I# (sizeofBigNat# bn) > 0
+
{-# RULES
"fromIntegral/Natural->Natural" fromIntegral = id :: Natural -> Natural
"fromIntegral/Natural->Integer" fromIntegral = toInteger :: Natural->Integer
@@ -397,6 +409,15 @@ naturalToInt (NatJ# bn) = I# (bigNatToInt bn)
newtype Natural = Natural Integer -- ^ __Invariant__: non-negative 'Integer'
deriving (Eq,Ord,Ix)
+-- | Test whether all internal invariants are satisfied by 'Natural' value
+--
+-- This operation is mostly useful for test-suites and/or code which
+-- constructs 'Integer' values directly.
+--
+-- /Since: 4.8.0.0/
+isValidNatural :: Natural -> Bool
+isValidNatural (Natural i) = i >= 0
+
instance Read Natural where
readsPrec d = map (\(n, s) -> (Natural n, s))
. filter ((>= 0) . (\(x,_)->x)) . readsPrec d