隨機生成自定義型別的資料

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
        ]