liveBook · Manning

Generator

As explained in Functional Programming in Scala, Second Edition

A generator is a parameterized representation of a computation that produces test-case values, potentially for any element type.

A generator is a parameterized representation of a computation that produces test-case values. A Gen[A] knows how to generate values of type A, such as lists of random integers, and can be combined with predicates to test properties. section 8.1 section 8.1.2

Generating lists for properties

val intList = Gen.listOf(Gen.choose(0, 100)) val prop = Prop.forAll(intList)(ns => ns.reverse.reverse == ns) && Prop.forAll(intList)(ns => ns.headOption == ns.reverse.lastOption) The generator supplies lists of varying lengths and values. ScalaCheck samples them, reporting success when generated cases satisfy both predicates and printing a counterexample when one fails. section 8.1

Generators become useful through a small, composable API:

  • Use listOf to lift Gen[A] into Gen[List[A]], keeping the operation polymorphic across element types. section 8.1.2
  • Represent Gen[A] as a State transition over an RNG, making random generation an explicit functional computation. section 8.1.4
  • Use flatMap when a generated value determines the next generator; use union and weighted to combine alternative generators. section 8.1.5
opaque type Gen[+A] = State[RNG, A]

Browse the compact representation that connects generators with explicit random-state transitions. section 8.1.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines Gen[A], develops combinators, and descends to State[RNG, A]; leaves function generation as an open challenge.
Examples
Uses integer ranges, lists, dependent string pairs, dynamically sized lists, unions, weighted choices, and takeWhile properties.
What it assumes
Assumes familiarity with typed functions and random-state computation while developing generator abstractions from concrete testing examples.
What you can do after
Build it from scratch with choose, unit, boolean, listOfN, flatMap, union, and weighted.
How it connects
Connects property-based testing, random number generation, State, combinators, properties, and higher-order functions.

Also explained in

Compare how 12 books explain generator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.