liveBook · Manning

Chooser

As explained in Functional Programming in Scala, Second Edition

chooser is a parallel-computation combinator that runs an initial computation and uses its result to generate or select a second computation.

chooser runs an initial parallel computation, uses its result to generate or select a second computation, and then runs that computation. Its generality makes fixed containers such as lists or maps unnecessary. section 7.4

Use chooser to express earlier selection combinators:

  • choice maps a Boolean result to either the true or false computation. section 7.9
  • choiceN uses the result as an index into a list of computations. section 7.9
  • choiceMap uses the result as a key for a map of computations. section 7.4
  • flatMap gives the operation its usual functional-programming form: transform a result into a new parallel computation. section 7.4

Defining selection through chooser

The core implementation first runs pa, obtains a, applies choices(a), and runs the resulting computation: extension [A](pa: Par[A]) def chooser[B](choices: A => Par[B]): Par[B] = es => { val a = pa.run(es).get; choices(a).run }. Then choice becomes pa.chooser(b => if b then t else f), while choiceN becomes n.chooser(i => choices(i % choices.size)). section 7.9

extension [A](pa: Par[A]) def chooser[B](choices: A => Par[B]): Par[B]

Inspect the compact chooser extension and compare its result-dependent computation selection with flatMap and join. section 7.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains the implementation and generalizes choice, choiceN, and choiceMap, then connects chooser to flatMap and join.
Examples
Demonstrates Boolean selection, indexed list selection, map lookup, and result-dependent computation generation.
What it assumes
Assumes familiarity with Par computations, run, choice, choiceN, choiceMap, and mapping computations.
What you can do after
Build it from scratch and implement choice and choiceN using chooser.
How it connects
Connects chooser to choice, choiceN, choiceMap, flatMap, join, and map.

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.