Search code examples
haskellquickcheck

Generating a lists of a specific length with Haskell's QuickCheck


-- 3 (find k"th element of a list)
element_at xs x = xs !! x
prop_3a xs x = (x < length xs && x >= 0) ==> element_at xs (x::Int) == (xs !! x::Int)

When prop_3a is ran through QuickCheck, it gives up, because it won't generate long enough lists.

How can I write a generator that will generate lists with length longer than the random integer?


Solution

  • How about going the other way? First we let QuickCheck pick a list and then we constrain what indices we allow. This works, and does not throw away any test cases.

    prop_3a (NonEmpty xs) = forAll (choose (0, length xs - 1)) $ \i ->
        element_at xs i == (xs !! i :: Int)
    

    Here, I use forAll to use a specific generator for the indices, in this case using choose which picks an element from a specified range, and I also use the NonEmptyList type to ensure that we don't try to index into an empty list.