liveBook · Manning

Gen

As explained in Learn Haskell by Example

Gen is a QuickCheck type representing a computation that generates randomized values of a specified type.

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

How Learn Haskell by Example covers it

How deep it goes
Defines typed random generation and demonstrates combinators, constrained generators, and Arbitrary instances, while deferring shrinking.
Examples
Uses alphabet-rotation data, AssocMap values, arbitrary integers, lists, Maybe values, Either values, and generated permutations.
What it assumes
Assumes familiarity with Haskell do notation and IO actions while introducing typed random generation and Arbitrary.
What you can do after
Apply via QuickCheck by constructing generators, running them with generate, and supplying structured data to property tests.
How it connects
Connects Gen to QuickCheck, Arbitrary, property testing, Functor mapping, IO actions, and shrinking.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.