Gen is a QuickCheck computation that describes how to generate randomized values of a particular type. Use generate to run one in IO, or obtain one automatically through Arbitrary. section 9.4.1 section 9.4
Build useful generators by combining standard operations:
- choose generates values within an interval; chooseAny converts a Random instance; elements selects from a list. section 9.4.1
- oneof selects among generators, suchThat rejects unwanted results, and listOf, listOf1, vectorOf, shuffle, and sublistOf create collections or permutations. section 9.4.1
- Use do notation to combine generated values, then map or combine them into a domain-specific value while preserving its invariants. section 9.4.1 section 9.4.2
Generating an associative map
A generator for AssocMap removes duplicate keys, creates the same number of arbitrary values, and zips both lists into the map: genAssocMap = do { keys <- L.nub <$> arbitrary; vals <- vectorOf (L.length keys) arbitrary; return $ AssocMap (L.zip keys vals) }. Its constraints require Eq k, Arbitrary k, and Arbitrary v. section 9.4.2
Listing 9.17 A QuickCheck generator for test data on the alphabet rotation function
gen :: Gen (Alphabet, Int, Char) gen = do size <- getSize #1 alphabet <- arbitrary `suchThat` (not . null) #2 n <- choose (-size, size) #3 c <- elements alphabet #4 return (alphabet, n, c) #5
Use a typed generator for alphabet rotation tests: select a nonempty alphabet, constrain the rotation amount with getSize and choose, then select a character from that alphabet. section 9.4.1
