Generic random generators
Go to file
2020-03-21 19:15:35 -04:00
examples Allow custom generator lists to not be terminated by ":+ ()" 2019-09-06 17:56:26 -04:00
src/Generic doc: word smith tutorial 2020-03-21 19:13:36 -04:00
test test: add inspection tests 2019-09-16 19:32:33 -04:00
.travis.yml Add 8.6 to CI 2018-10-01 14:49:48 -04:00
CHANGELOG.md CHANGELOG: Update 2020-03-21 19:15:35 -04:00
generic-random.cabal doc: Typesetting doesn't work in synopsis 2020-03-20 20:10:17 -04:00
LICENSE Initial commit 2016-04-06 23:34:02 +02:00
README.md doc: Add more prominent mentions of Arbitrary 2020-03-20 19:51:25 -04:00
Setup.hs Initial commit 2016-04-06 23:34:02 +02:00

Generic random generators Hackage Build Status

Generic random generators to implement Arbitrary instances for QuickCheck

Automating the arbitrary boilerplate also ensures that when a type changes to have more or fewer constructors, then the generator either fixes itself to generate that new case (when using the uniform distribution) or causes a compilation error so you remember to fix it (when using an explicit distribution).

This package also offers a simple (optional) strategy to ensure termination for recursive types: make Test.QuickCheck.Gen's size parameter decrease at every recursive call; when it reaches zero, sample directly from a trivially terminating generator given explicitly (genericArbitraryRec and withBaseCase) or implicitly (genericArbitrary').

Example

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics (Generic)
import Test.QuickCheck
import Generic.Random

data Tree a = Leaf | Node (Tree a) a (Tree a)
  deriving (Show, Generic)

instance Arbitrary a => Arbitrary (Tree a) where
  arbitrary = genericArbitraryRec uniform `withBaseCase` return Leaf

-- Equivalent to
-- > arbitrary =
-- >   sized $ \n ->
-- >     if n == 0 then
-- >       return Leaf
-- >     else
-- >       oneof
-- >         [ return Leaf
-- >         , resize (n `div` 3) $
-- >             Node <$> arbitrary <*> arbitrary <*> arbitrary
-- >         ]

main :: IO ()
main = sample (arbitrary :: Gen (Tree ()))