我有两台发电机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)
答案 0 :(得分:8)
(i)您可以使用普通的functorial / monadic组合来组合它们:
gen_comb :: Gen (Int, [Int])
gen_comb = (,) <$> gen_elem <*> gen_arr
(Control.Applicative.liftA2
和Control.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或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
生成器没有输出任何内容。