Alex Rivera | Logout

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

Asked 2012-10-10T20:32:11.843
16

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?

Edit
Report

1 Answer

10

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.

answered 2012-10-10T20:46:35.260

Your Answer