Skip to content

Instantly share code, notes, and snippets.

@csoroz
Created June 21, 2019 11:25
Show Gist options
  • Save csoroz/51b2cb387bd91d983ef1240bbfd6459f to your computer and use it in GitHub Desktop.
Save csoroz/51b2cb387bd91d983ef1240bbfd6459f to your computer and use it in GitHub Desktop.
Unit Interval QuickCheck [0,1]
import qualified Data.Fixed as FP
import Test.QuickCheck
data E34
instance FP.HasResolution E34 where
resolution _ = 10^34
type FixedPoint = FP.Fixed E34
newtype UnitInterval a = Unit a deriving Show
instance (Fractional a, Arbitrary a) => Arbitrary (UnitInterval a) where
arbitrary = return . Unit . toUnit =<< arbitrary
type NonNegInts = (NonNegative Integer, Positive Integer)
normalizeInts :: NonNegInts -> (Integer,Integer)
normalizeInts (NonNegative x, Positive y) = (min x y, max x y)
normalize :: Fractional a => NonNegInts -> (a,a)
normalize = mapp fromInteger . normalizeInts
where mapp f (x,y) = (f x, f y)
toUnit :: Fractional a => NonNegInts -> a
toUnit = uncurry (/) . normalize -- [0,1]
prop_Unit :: UnitInterval FixedPoint -> Property
prop_Unit (Unit x) = classify (x==1) "= 1" $
classify (x==0) "= 0" $
(0 <= x && x <= 1) === True
main = quickCheck (withMaxSuccess 100000 prop_Unit)
@csoroz
Copy link
Author

csoroz commented Jun 21, 2019

Testing QuickCheck Arbitrary instance of Unit Interval [0,1] with Fixed Point arithmetic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment