liveBook · Manning

Flatmap

As explained in Fabulous Adventures in Data Structures and Algorithms

FlatMap is an operation that maps each element to a sequence and concatenates the resulting sequences into one sequence.

FlatMap maps each element to a sequence, then concatenates those sequences into one. In C#, the equivalent operation is SelectMany. section 11.4

    public static IEnumerable<R> SelectMany<T, R>(
        this IEnumerable<T> items,
        Func<T, IEnumerable<R>> func)
    {
        foreach(T t in items)
            foreach(R r in func(t))
                yield return r;
    }
    public static IEnumerable<R> SelectMany<T, U, R>(
        this IEnumerable<T> items,
        Func<T, IEnumerable<U>> func,
        Func<T, U, R> projection)
    {
        foreach(T t in items)
            foreach(U u in func(t))
                yield return projection(t, u);
    }

The nested iteration makes the operation explicit: the outer loop visits source elements, while the inner loop emits every element from each resulting sequence. section 11.4

FlatMap supports several closely related ideas:

  • It avoids producing a sequence of sequences by concatenating each mapped result immediately. section 11.4
  • It corresponds to Bind for the sequence monad; Select corresponds to Map, and Join removes one nesting level. section 11.5
  • It can represent filtering by mapping each item to either a one-element sequence or an empty sequence. section 11.4

Backtracking with SelectMany

A general backtracker recursively explores every possible value for an unresolved key. Each recursive call returns a sequence of solutions, and SelectMany concatenates those sequences into one solution stream. The same pattern solves Sudoku after a reducer eliminates impossible candidates. section 8.5.2

The technique is useful when one choice expands into many choices and the results must remain uniformly composable. It also supports readable sequence-based code for manipulating random quantities. section 12.0 section 11.5

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Defines flatMap, derives its C# implementation, connects it to monadic operations, and demonstrates recursive search.
Examples
Uses nested C# iteration, zero-or-one-element filtering, graph-coloring search, and Sudoku solving.
What it assumes
Assumes familiarity with sequences, mapping, recursion, and generic functions while connecting them to monadic terminology.
What you can do after
Build it from scratch as nested iteration and apply it to concatenate branching solution sequences.
How it connects
Connects flatMap with SelectMany, Bind, Map, Join, Unit, Where, sequence monads, and backtracking search.

Also explained in

Compare how 5 books explain flatmap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.