Learning path

Full curriculum

Full curriculum

Unit content

FlatMap, bind and monadic composition

When a function already returns a contextual value,

$$f:A\to M,$$

mapping it over $M$ would produce a nested result $M<M>$. flatMap—also called bind—combines mapping with the appropriate flattening:

$$\operatorname{flatMap}:M\times(A\to M)\to M.$$

For Option, None stops the chain and Some(a) continues with $f(a)$. For Result, an error passes through while a success supplies its value to the next computation.

Composition in context

Given

$$f:A\to M,\qquad g:B\to M,$$

bind lets them compose without repeatedly unpacking the context:

input
  → f
  → flatMap(g)
  → contextual result

A constructor such as pure, return or Some places an ordinary value into the context.

Monad laws

A context with a value-injection operation and bind is monadic when composition behaves coherently. In practical terms, inserting a value and immediately binding should act like the original computation, and regrouping a chain of binds should not change its meaning. These are the identity and associativity laws.

The laws matter because they make contextual computations composable like ordinary functions rather than as an ad-hoc sequence of special cases.

What a monad is useful for

Option and Result make absence and failure composable. Other monadic interfaces can thread state, asynchronous computations or other effects through a pipeline. The abstraction is valuable when it removes repeated control-flow plumbing; it is not a requirement that every program be expressed in monadic style.