QuickCheck:根据其他Arbitraries定义任意实例

时间:2011-02-27 16:13:15

标签: haskell quickcheck

我正在使用QuickCheck 1,我有以下数据类型:

data A = ...
instance Arbitrary A where ...
data B = ...
instance Arbitrary B where ...
data C = C A B

现在,我想为Arbitrary定义C个实例,以便使用CA的现有生成器生成B个值。我最终这样做了:

instance Arbitrary C where
  arbitrary = elements [(C a b) |
                        a <- generate 20 (System.Random.mkStdGen 0) arbitrary,
                        b <- generate 20 (System.Random.mkStdGen 0) arbitrary]

是否需要AB明确生成固定数量的值,还是有更好的方法将现有Arbitraries合并为新的?{/ p>

1 个答案:

答案 0 :(得分:20)

我会这样做:

instance Arbitrary C
  where arbitrary = do a <- arbitrary
                       b <- arbitrary
                       return (C a b)

尽管sclv使用Control.Monad中liftM2的想法可能更好:

instance Arbitrary C
  where arbitrary = liftM2 C arbitrary arbitrary