packages feed

papa-0.7.0: test/PropertiesNumeric.hs

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

{- HLINT ignore "Avoid restricted function" -}
-- Reason: these properties compare Papa's total functions with the partial
-- ones of Papa.Unsafe.Numeric and Prelude, whose names HLint restricts.

-- | The agreement of Papa's total numeric functions with the partial ones of
-- "Papa.Unsafe.Numeric" and "Prelude", at every numeric type of base.
module PropertiesNumeric (
  propertiesNumeric,
) where

import Agree (agrees, agreesWhereDefined)
import Data.Fixed (Centi, Fixed (MkFixed), mod')
import Hedgehog (Gen, Group (Group), Property, PropertyName, Range, assert, forAll, property, (===))
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Papa
import Papa.Unsafe.Numeric (Natural)
import qualified Papa.Unsafe.Numeric as U
import qualified Prelude as P

-- | Every property of this module, in one group.
propertiesNumeric :: Group
propertiesNumeric =
  Group (fromString "papa: numeric agreement") (integrals <> fractionals <> conversions)

-- | One named property.
prop :: String -> Property -> [(PropertyName, Property)]
prop name p =
  [(fromString name, p)]

-- Integral types

-- | The total integral functions at every integral type of base.
integrals :: [(PropertyName, Property)]
integrals =
  bounded "Int" (genBounded Gen.int) (preview nonZero)
    <> bounded "Int8" (genBounded Gen.int8) (preview nonZero)
    <> bounded "Int16" (genBounded Gen.int16) (preview nonZero)
    <> bounded "Int32" (genBounded Gen.int32) (preview nonZero)
    <> bounded "Int64" (genBounded Gen.int64) (preview nonZero)
    <> bounded "Word" (genBounded Gen.word) (preview nonZero)
    <> bounded "Word8" (genBounded Gen.word8) (preview nonZero)
    <> bounded "Word16" (genBounded Gen.word16) (preview nonZero)
    <> bounded "Word32" (genBounded Gen.word32) (preview nonZero)
    <> bounded "Word64" (genBounded Gen.word64) (preview nonZero)
    <> integral "Integer" genInteger (preview nonZero)
    <> integral "Natural" genNatural (preview nonZero)
    <> prop "ratioNonZero agrees with (%) at Integer" (property (do n <- forAll genInteger; d <- forAll genInteger; agrees (fmap (ratioNonZero n) (preview nonZero d)) (n U.% d)))

-- | A bounded integral type: its ends, the values next to them, and @-1@,
-- often.
genBounded :: (Integral a, Bounded a) => (Range a -> Gen a) -> Gen a
genBounded g =
  Gen.frequency
    [ (1, Gen.element [0, 1, 2, U.fromInteger (-1), U.fromInteger (-2), minBound, maxBound, minBound + 1, maxBound - 1])
    , (4, g Range.linearBounded)
    ]

genInteger :: Gen Integer
genInteger =
  Gen.frequency
    [ (1, Gen.element [0, 1, -1, 2, -2])
    , (4, Gen.integral (Range.exponentialFrom 0 (negate (pow 10 30)) (pow 10 30)))
    ]

genNatural :: Gen Natural
genNatural =
  Gen.frequency
    [ (1, Gen.element [0, 1, 2])
    , (4, Gen.integral (Range.exponential 0 (pow 10 30)))
    ]

-- | The properties of an integral type that is 'Bounded': those of every
-- integral type, and 'pred'.
bounded :: (Integral a, Bounded a, Show a, NFData a) => String -> Gen a -> (a -> Maybe (NonZero a)) -> [(PropertyName, Property)]
bounded t g mk =
  integral t g mk
    <> prop ("pred agrees with Prelude's at " <> t) (property (do x <- forAll g; agrees (pred x) (P.pred x)))

-- | The properties of every integral type: each total function agrees with
-- its partial counterpart wherever that is defined.
integral :: forall a. (Integral a, Show a, NFData a) => String -> Gen a -> (a -> Maybe (NonZero a)) -> [(PropertyName, Property)]
integral t g mk =
  prop ("nonZero is Nothing exactly at 0 at " <> t) (property (do d <- forAll g; isNothing (mk d) === (d == 0)))
    <> division "divNonZero" divNonZero U.div
    <> division "modNonZero" modNonZero U.mod
    <> division "divModNonZero" divModNonZero U.divMod
    <> division "quotNonZero" quotNonZero U.quot
    <> division "remNonZero" remNonZero U.rem
    <> division "quotRemNonZero" quotRemNonZero U.quotRem
    <> prop ("pow agrees with (^) at " <> t) (property (do x <- forAll g; e <- forAll (Gen.integral (Range.linear 0 20)); pow x e === x U.^ e))
    <> prop ("succ agrees with Prelude's at " <> t) (property (do x <- forAll g; agrees (succ x) (P.succ x)))
 where
  division :: (Eq r, Show r, NFData r) => String -> (a -> NonZero a -> r) -> (a -> a -> r) -> [(PropertyName, Property)]
  division name total partial =
    prop
      (name <> " agrees with Papa.Unsafe.Numeric at " <> t)
      (property (do n <- forAll g; d <- forAll g; for_ (mk d) (\nz -> agreesWhereDefined (total n nz) (partial n d))))

-- Fractional types

-- | The total fractional functions at 'Float', 'Double' and 'Rational'.
fractionals :: [(PropertyName, Property)]
fractionals =
  fractional "Float" genFloat (preview nonZero)
    <> fractional "Double" genDouble (preview nonZero)
    <> fractional "Rational" genRational (preview nonZero)
    <> floating "Double" genDouble cFloor cCeil cTrunc cRint
    <> floating "Float" genFloat cFloorf cCeilf cTruncf cRintf
    <> modulus

foreign import ccall unsafe "math.h floor" cFloor :: Double -> Double
foreign import ccall unsafe "math.h ceil" cCeil :: Double -> Double
foreign import ccall unsafe "math.h trunc" cTrunc :: Double -> Double
foreign import ccall unsafe "math.h rint" cRint :: Double -> Double
foreign import ccall unsafe "math.h floorf" cFloorf :: Float -> Float
foreign import ccall unsafe "math.h ceilf" cCeilf :: Float -> Float
foreign import ccall unsafe "math.h truncf" cTruncf :: Float -> Float
foreign import ccall unsafe "math.h rintf" cRintf :: Float -> Float

-- | The total floating-point functions at a floating type. The rounding
-- functions agree with C's (@rint@ rounds a half to even in the default
-- rounding mode), including at @NaN@, the infinities and @-0@: results are
-- compared as shown, so that @NaN@ equals @NaN@ and @-0@ differs from @0@.
floating :: (RealFloat a, Show a) => String -> Gen a -> (a -> a) -> (a -> a) -> (a -> a) -> (a -> a) -> [(PropertyName, Property)]
floating t g f c u r =
  prop ("divideFloating agrees with (/) at " <> t) (property (do x <- forAll g; d <- forAll g; show (divideFloating x d) === show (x U./ d)))
    <> prop ("recipFloating agrees with recip at " <> t) (property (do d <- forAll g; show (recipFloating d) === show (U.recip d)))
    <> prop ("floorFloating agrees with C's floor at " <> t) (property (do x <- forAll g; show (floorFloating x) === show (f x)))
    <> prop ("ceilingFloating agrees with C's ceil at " <> t) (property (do x <- forAll g; show (ceilingFloating x) === show (c x)))
    <> prop ("truncateFloating agrees with C's trunc at " <> t) (property (do x <- forAll g; show (truncateFloating x) === show (u x)))
    <> prop ("roundFloating agrees with C's rint at " <> t) (property (do x <- forAll g; show (roundFloating x) === show (r x)))

-- | 'modFloating' at 'Double': "Data.Fixed"'s @mod'@, exactly, then rounded,
-- for a finite dividend and a finite divisor that is not zero; in the closed
-- interval from zero to the divisor; @NaN@ elsewhere, except for an infinite
-- divisor.
modulus :: [(PropertyName, Property)]
modulus =
  prop "modFloating: Data.Fixed's mod' at Rational, rounded" (property (do x <- forAll genDouble; y <- forAll genDouble; when (finiteFloating x && finiteFloating y && y /= 0) (modFloating x y === P.fromRational (mod' (P.toRational x) (P.toRational y)))))
    <> prop "modFloating: from zero to the divisor, with its sign" (property (do x <- forAll genDouble; y <- forAll genDouble; when (finiteFloating x && finiteFloating y && y /= 0) (let m = modFloating x y in assert (bool (m <= 0 && m >= y) (m >= 0 && m <= y) (y > 0)))))
    <> prop "modFloating: NaN for a divisor of zero or NaN, or a dividend that is not finite" (property (do x <- forAll genDouble; y <- forAll genDouble; when (not (finiteFloating x) || isNaN y || y == 0) (assert (isNaN (modFloating x y)))))

-- | @NaN@, an infinity, and the largest finite and least positive 'Double'.
nan, infinity, maxFinite, minSubnormal :: Double
nan = 0 U./ 0
infinity = 1 U./ 0
maxFinite = 1.7976931348623157e308
minSubnormal = 5.0e-324

-- | Values at which rounding and conversion change: halves, the ends of
-- the integral types, and the values that are not finite.
specialDoubles :: [Double]
specialDoubles =
  [0, negate 0, 0.5, -0.5, 1.5, 2.5, -2.5, 127.5, 128, -128.5, -129, 255.5, 256, 9.223372036854775807e18, -9.223372036854775808e18, 1.8446744073709552e19, maxFinite, negate maxFinite, minSubnormal, nan, infinity, negate infinity]

genDouble :: Gen Double
genDouble =
  Gen.frequency
    [ (1, Gen.element specialDoubles)
    , (4, Gen.double (Range.exponentialFloatFrom 0 (-1.0e300) 1.0e300))
    ]

genFloat :: Gen Float
genFloat =
  Gen.frequency
    [ (1, Gen.element (fmap doubleToFloat specialDoubles))
    , (4, Gen.float (Range.exponentialFloatFrom 0 (-1.0e30) 1.0e30))
    ]

genRational :: Gen Rational
genRational =
  ratioNonZero <$> genInteger <*> Gen.just (preview nonZero <$> genInteger)

genCenti :: Gen Centi
genCenti =
  MkFixed <$> genInteger

-- | Whether a value of a floating type is finite.
finiteFloating :: (RealFloat a) => a -> Bool
finiteFloating x =
  not (isNaN x || isInfinite x)

-- | The properties of a fractional type: each total function agrees with
-- its partial counterpart wherever that is defined. Results are compared
-- as shown, so that @NaN@ equals @NaN@ and @-0@ differs from @0@.
fractional :: (Eq a, Fractional a, Show a) => String -> Gen a -> (a -> Maybe (NonZero a)) -> [(PropertyName, Property)]
fractional t g mk =
  prop ("nonZero is Nothing exactly at 0 at " <> t) (property (do d <- forAll g; isNothing (mk d) === (d == 0)))
    <> prop ("divideNonZero agrees with (/) at " <> t) (property (do x <- forAll g; d <- forAll g; for_ (mk d) (\nz -> agreesWhereDefined (show (divideNonZero x nz)) (show (x U./ d)))))
    <> prop ("recipNonZero agrees with recip at " <> t) (property (do d <- forAll g; for_ (mk d) (\nz -> agreesWhereDefined (show (recipNonZero nz)) (show (U.recip d)))))
    <> prop ("powNonZero agrees with (^^) at " <> t) (property (do d <- forAll g; e <- forAll (Gen.int (Range.linear (-20) 20)); for_ (mk d) (\nz -> agreesWhereDefined (show (powNonZero nz e)) (show (d U.^^ e)))))

-- Conversions

-- | The total conversions from fractional types, and between floating
-- types.
conversions :: [(PropertyName, Property)]
conversions =
  fromFractional "Float" genFloat finiteFloating
    <> fromFractional "Double" genDouble finiteFloating
    <> fromFractional "Rational" genRational (const True)
    <> fromFractional "Centi" genCenti (const True)
    <> prop "floatToDouble agrees with realToFrac at finite values, and keeps NaN, the infinities and -0" (property (do x <- forAll genFloat; when (finiteFloating x) (floatToDouble x === U.realToFrac x); (isNaN (floatToDouble x), isInfinite (floatToDouble x), isNegativeZero (floatToDouble x)) === (isNaN x, isInfinite x, isNegativeZero x)))
    <> prop "doubleToFloat agrees with realToFrac at finite values, and keeps NaN, the infinities and -0" (property (do x <- forAll genDouble; when (finiteFloating x) (doubleToFloat x === U.realToFrac x); when (isInfinite x) (floatToDouble (doubleToFloat x) === x); (isNaN (doubleToFloat x), isNegativeZero (doubleToFloat x)) === (isNaN x, isNegativeZero x)))
    <> prop "doubleToFloat . floatToDouble is the identity" (property (do x <- forAll genFloat; show (doubleToFloat (floatToDouble x)) === show x))
    <> toFloating "Int" (genBounded Gen.int)
    <> toFloating "Int8" (genBounded Gen.int8)
    <> toFloating "Int64" (genBounded Gen.int64)
    <> toFloating "Word" (genBounded Gen.word)
    <> toFloating "Word64" (genBounded Gen.word64)
    <> toFloating "Integer" genInteger
    <> toFloating "Natural" genNatural
    <> prop "integralToFloating rounds an Integer to the nearest Double" (property (do n <- forAll genInteger; integralToFloating n === (fromRational (U.fromInteger n) :: Double)))

-- | 'integralToFloating' agrees with @fromIntegral@ at 'Double' and 'Float'.
toFloating :: (Integral a, Show a) => String -> Gen a -> [(PropertyName, Property)]
toFloating t g =
  prop ("integralToFloating agrees with fromIntegral from " <> t) (property (do n <- forAll g; (integralToFloating n :: Double, integralToFloating n :: Float) === (U.fromIntegral n, U.fromIntegral n)))

-- | The total conversions from a fractional type, to each integral type.
fromFractional :: (RealFrac a, Show a) => String -> Gen a -> (a -> Bool) -> [(PropertyName, Property)]
fromFractional t g fin =
  rounding t g fin "Int" (Proxy :: Proxy Int)
    <> rounding t g fin "Int8" (Proxy :: Proxy Int8)
    <> rounding t g fin "Word" (Proxy :: Proxy Word)
    <> rounding t g fin "Word8" (Proxy :: Proxy Word8)
    <> rounding t g fin "Integer" (Proxy :: Proxy Integer)
    <> rounding t g fin "Natural" (Proxy :: Proxy Natural)
    <> prop ("toRationalMaybe: Prelude's toRational at finite values, else Nothing, at " <> t) (property (do x <- forAll g; toRationalMaybe x === bool Nothing (Just (U.toRational x)) (fin x)))

-- | Each total rounding function from a fractional type to an integral type
-- is 'Nothing' at values that are not finite and at results out of the
-- range of the target, and "Prelude"'s everywhere else.
rounding :: forall a b. (RealFrac a, Show a, Integral b, Bits b, Show b) => String -> Gen a -> (a -> Bool) -> String -> Proxy b -> [(PropertyName, Property)]
rounding t g fin u _ =
  method "truncateMaybe" truncateMaybe U.truncate
    <> method "roundMaybe" roundMaybe U.round
    <> method "ceilingMaybe" ceilingMaybe U.ceiling
    <> method "floorMaybe" floorMaybe U.floor
    <> prop
      ("properFractionMaybe: Prelude's where finite and in range, at " <> t <> " -> " <> u)
      ( property
          ( do
              x <- forAll g
              let (n, f) = U.properFraction x :: (Integer, a)
              (properFractionMaybe x :: Maybe (b, a)) === bool Nothing ((,f) <$> toIntegralSized n) (fin x)
          )
      )
 where
  method :: String -> (a -> Maybe b) -> (forall c. (Integral c) => a -> c) -> [(PropertyName, Property)]
  method name total partial =
    prop
      (name <> ": Prelude's where finite and in range, at " <> t <> " -> " <> u)
      ( property
          ( do
              x <- forAll g
              total x === bool Nothing (toIntegralSized (partial x :: Integer)) (fin x)
              for_ (total x) (\n -> n === partial x)
          )
      )