How to tell QuickCheck to generate only valid list indices for a parameter?

≡放荡痞女 提交于 2019-12-10 00:58:25

问题


Say I want to write some unit tests for the (!!) function.

my_prop xs n = ...

I want to restrict n to only valid indexes and I know I could do something like

my_prop xs n = (not.null) (drop n xs) ==> ...

But this makes it so that the vast majority of the generated cases are invalid and get thrown away. Is there a way I can set things up so that QuickCheck generates the xs list first and uses its value to generate only valid cases of n?


回答1:


Using forAll, you can specify a generator for n which depends on the earlier arguments, e.g.

my_prop (NonEmpty xs) = forAll (choose (0, length xs - 1)) $ \n -> ...



回答2:


You can make a generator that only creates valid indices and write your property like

import Test.QuickCheck
import Test.QuickCheck.Gen
import System.Random

indices :: [a] -> Gen Int
indices xs = MkGen $ \sg _ -> fst $ randomR (0, length xs - 1) sg

my_prop :: [Char] -> Property
my_prop xs = not (null xs) ==> forAll (indices xs) (\i -> xs !! i /= '0')

eliminating the Int argument.




回答3:


As suggested by Daniel Wagner, one possibility is creating my own datatype and giving it an Arbitrary instance.

data ListAndIndex a = ListAndIndex [a] Int deriving (Show)

instance Arbitrary a => Arbitrary (ListAndIndex a) where
   arbitrary = do
     (NonEmpty xs) <- arbitrary
     n  <- elements [0..(length xs - 1)]
     return $ ListAndIndex xs n

NonEmpty is from a custom type in Test.QuickCheck.Modifiers for generating non empty lists.



来源:https://stackoverflow.com/questions/12827861/how-to-tell-quickcheck-to-generate-only-valid-list-indices-for-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!