Search code examples
haskellquickcheck

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


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?


Solution

  • 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 -> ...