liveBook · Manning

Map

As explained in Fabulous Adventures in Data Structures and Algorithms

A monadic map operation applies a function to values inside a monadic computational context while preserving that context's structure.

Map applies an ordinary function to a value inside a monadic context, producing a new context while preserving capabilities such as laziness, nullability, asynchrony, or sequencing. section 11.3 section 11.0

static class LazyExtensions
{
    public static Lazy<R> Map<T, R>(this Lazy<T> x, Func<T, R> func) =>
        new Lazy<R>(() => func(x.Value));
}

A Lazy<T> Map implementation delays evaluation and applies the function only when the resulting Lazy<R> is evaluated. section 11.3

Mapping a lazy value

Given a Lazy<int> and a regular function such as DivTwo, Map produces a Lazy<double>. The function remains ordinary; Map supplies the laziness around it. Applying Map to a function that already returns Lazy<double>, however, produces Lazy<Lazy<double>>, an unnecessarily nested context. section 11.3

Map generalizes the same transformation across several computational contexts:

  • Nullable<T> preserves nullability while mapping a value. section 11.3
  • Task<T> preserves asynchrony while mapping a completed result. section 11.3
  • IEnumerable<T> maps elements while retaining sequence structure. section 11.3
  • Bind handles functions that already return monadic values; Map can be derived by binding after Unit wraps the ordinary result. section 11.3 section 11.5

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Defines Map, implements it for Lazy<T>, relates it to Bind and Unit, and stops short of detailed implementations for every context.
Examples
Uses Lazy<int>, DivTwo, Nullable<T>, Task<T>, IEnumerable<T>, and the nested Lazy<Lazy<double>> problem.
What it assumes
Assumes generic types, functions returning regular or monadic values, and basic familiarity with monadic capabilities.
What you can do after
Apply Map to lift ordinary functions into lazy, nullable, asynchronous, or sequence-based workflows and recognize when Bind is required.
How it connects
Connects Map to monads, Unit, Bind, Join, lazy evaluation, nullability, asynchrony, and sequence operations.

Also explained in

Compare how 8 books explain map →

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.