liveBook · Manning

Union

As explained in Functional Programming in Scala, Second Edition

union is a generator combinator that combines two generators of the same type and selects between them with equal likelihood.

union combines two generators of the same type into one generator, choosing between them with equal likelihood. It turns a boolean coin flip into a generator-selection decision. section 8.1.5 section 8.6

Selecting a generator with a coin flip

def union[A](g1: Gen[A], g2: Gen[A]): Gen[A] = boolean.flatMap(b => if b then g1 else g2) The boolean generator supplies the choice; flatMap uses that choice to select g1 or g2 as the next generator. The resulting Gen[A] preserves the common element type. section 8.6 section 8.1.5

def union[A](g1: Gen[A], g2: Gen[A]): Gen[A]

Inspect the compact union signature before comparing its implementation with the boolean-and-flatMap definition. section 8.1.5

Use union when:

  • Two alternative generators produce values of the same type. section 8.1.5
  • Each alternative should be selected with equal likelihood rather than custom probabilities. section 8.6
  • Selection must remain an explicit, composable generator rather than an immediate random choice. section 8.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines equal-likelihood selection and derives it from boolean and flatMap, without developing weighted selection internally.
Examples
Uses boolean.flatMap to choose g1 or g2, then contrasts union with weighted selection.
What it assumes
Assumes Gen and boolean generation, while using flatMap to teach dependent generator selection.
What you can do after
Build it from scratch by implementing union with a boolean generator and flatMap.
How it connects
Connects generators with flatMap, boolean generation, State, RNG, and weighted selection.

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.