Search code examples
haskellgeneratorquickcheck

Generating a list of integers that isn't equal to a specified integer in Haskell?


Is there a modifier that allows me to generate a list of integers that does not contain a specified integer?

This is a function that does the same job:

listofInts :: Int -> Gen [Integer]
listofInts  a = rmInt a [] arbitrary

rmInt :: Int -> [Int] -> [Int] -> [Int]
rmInt a newList [] = newList
rmInt a newList (x:xs)
|a == x = newList : rmInt a xs
|otherwise = newList : x : rmInt a xs

Solution

  • The listOf and suchThat combinators from Test.QuickCheck.Gen should enable you to do that.

    listofInts :: Int -> Gen [Integer]
    listOfInts x = listOf (suchThat arbitrary (/=x))
    

    This approach have the advantage to be more respectful of the size parameter for the generation: suchThat ensures that a generated value that doesn't match the predicate does not influence the size.