Skip to content

Instantly share code, notes, and snippets.

instance Arbitrary Int where
arbitrary = Gen $ \rand -> fst (next rand)
prop_gcd_overflow :: Int -> Int -> Bool
prop_gcd_overflow a b = a * b == gcd a b * lcm a b
rapidCheck prop_gcd_overflow
> Failure {seed = -881134321,
counterExample = ["171542757","1235104953"]}
prop_gcd :: Integer -> Integer -> Bool
prop_gcd a b = a * b == gcd a b * lcm a b
prop_partition :: [Integer] -> (Integer -> Bool) -> Bool
prop_partition xs p =
let (lhs, rhs) = partition p xs
in and
[ all p lhs
, not (any p rhs)
, sort xs == sort (lhs ++ rhs) ]
rapidCheck prop_partition
> Success
prop_distributive :: Integer -> Integer -> (Integer -> Integer) -> Bool
prop_distributive a b f = f (a + b) == f a + f b
rapidCheck prop_distributive
> Failure {seed = 7720540227186278723,
counterExample = ["1716301762","55093645","<function>"]}
promote :: (a -> Gen b) -> Gen (a -> b)
promote f =
Gen $ \rand a ->
runGen (f a) rand
class CoArbitrary a where
coarbitrary :: Gen b -> a -> Gen b
instance
(CoArbitrary a, Arbitrary b)
=> Arbitrary (a -> b)
where
arbitrary = promote (coarbitrary arbitrary)
instance CoArbitrary Integer where
coarbitrary gen n =
Gen $ \rand ->
runGen gen (perturb n rand)
perturb :: (Integral n) => n -> StdGen -> StdGen
perturb n rand0 =
foldl
(\rand b -> vary b rand) -- Vary generator based on digit value
(vary (n < 0) rand0) -- Vary generator based on sign
(digits (abs n)) -- Decompose a positive number in digits
where
vary digit rand =
(if digit then snd else fst)
(split rand)
instance CoArbitrary [Int] where
coarbitrary gen xs =
Gen $ \rand ->
runGen gen (foldr perturb (perturb 0 rand) xs)