QuickCheck:如何组合两个生成器?

QuickCheck: How to combine two generators?

我有两个生成器,gen_n & gen_arr:

gen_n :: Gen Int
gen_n = suchThat arbitrary (\i -> i >= 0 && i <= 10)

gen_elem :: Gen Int
gen_elem = suchThat arbitrary (\i -> i >= 0 && i <= 100)

gen_arr :: Gen [Int]
gen_arr = listOf gen_elem 

如何将这两个组合成一个Gen (Int, [Int])

combine_two_gens :: Gen a -> Gen b -> Gen (a, b)

(i) 你可以使用正常的 functorial/monadic 组合来组合它们:

gen_comb :: Gen (Int, [Int])
gen_comb = (,) <$> gen_elem <*> gen_arr

(当然Control.Applicative.liftA2Control.Monad.liftM2也可以)

(ii) 不要使用 suchThat 来限制范围。它可能非常低效,因为它只会生成随机实例,直到满足条件,然后丢弃其余实例。相反,您可以使用 elements :: [a] -> Gen a:

gen_elem' :: Gen Int
gen_elem' = elements [0..100]

gen_arr' :: Gen [Int]
gen_arr' = listOf gen_elem'

gen_comb' :: Gen (Int, [Int])
gen_comb' = (,) <$> elements [0..100] <*> listOf (elements [0..100])

更新: 正如 Zeta 在下面所说的,在这种情况下我们可以做得更好,使用 choose (0,100) (choose :: Random a => (a, a) -> Gen a) 而不是 elements [0..100].有关生成器组合器的完整列表,请参阅 here, or here


*Main> sample gen_arr'
[78]
[2,27]
[12,39]
[92,22,40,6,18,19,25,13,95,99]
...
*Main> sample gen_comb'
(9,[23,3])
(11,[67,38,11,79])
(5,[96,69,68,81,75,14,59,68])
...

suchThat 对比 elements

*Main> sample (suchThat arbitrary (\i -> i >= 10000 && i <= 10005))
^CInterrupted.
*Main> sample (elements [10000..10005])
10003
10002
10000
10000
...

suchThat 生成器没有输出任何内容。