liveBook · Manning

choiceN

As explained in Functional Programming in Scala, Second Edition

choiceN is a parallel-computation combinator that selects a computation from a list using the integer result of an initial computation.

choiceN runs an integer-valued parallel computation, waits for its result, and uses that integer to select and run one computation from a list. It generalizes Boolean choice from two alternatives to N alternatives. section 7.4 section 7.9

The combinator supports these related constructions:

  • Implement choice by mapping true to index 0 and false to index 1, then passing the resulting computation and a two-element list to choiceN. section 7.9
  • Replace the list with a keyed Map to obtain choiceMap; the lookup strategy changes while the sequencing pattern remains the same. section 7.4 section 7.9
  • Generalize further with chooser, which accepts a function from the initial result to the selected parallel computation; choiceN becomes a list lookup function. section 7.4 section 7.9

A direct implementation

def choiceN[A](n: Par[Int])(choices: List[Par[A]]): Par[A] = es => val index = n.run(es).get % choices.size choices(index).run(es) The initial computation is evaluated first. Its result selects a list position, and the selected Par is then run with the same execution context. section 7.9

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains evaluation, lookup, implementation, and derivation of choice, but defers broader execution concerns.
Examples
Uses Boolean choice, indexed List selection, keyed Map selection, and function-based chooser selection.
What it assumes
Assumes familiarity with Par, execution contexts, map, and running computations for results.
What you can do after
Build it from scratch and refactor Boolean or indexed selection into the more general chooser pattern.
How it connects
Connects parallel computation with choice, choiceMap, chooser, map, and flatMap.

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.