随机生成自定义类型的数据

Arbitrary 类适用于可由 QuickCheck 随机生成的类型。

Arbitrary 的最小实现是 arbitrary 方法,它在 Gen monad 中运行以产生随机值。

以下是 Arbitrary 的实例,用于以下非空列表的数据类型。

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
        ]