Haskell Language Randomly generating data for custom types


Example

The Arbitrary class is for types that can be randomly generated by QuickCheck.

The minimal implementation of Arbitrary is the arbitrary method, which runs in the Gen monad to produce a random value.

Here is an instance of Arbitrary for the following datatype of non-empty lists.

import Test.QuickCheck.Arbitrary (Arbitrary(..))
import Test.QuickCheck.Gen (oneof)
import Control.Applicative ((<$>), (<*>))

data NonEmpty a = End a | Cons a (NonEmpty a)

instance Arbitrary a => Arbitrary (NonEmpty a) where
    arbitrary = oneof [  -- randomly select one of the cases from the list
        End <$> arbitrary,  -- call a's instance of Arbitrary
        Cons <$>
            arbitrary <*>  -- call a's instance of Arbitrary
            arbitrary  -- recursively call NonEmpty's instance of Arbitrary
        ]