read it as a refactor: two passes fuse into one, same result
here F = Array · F(f) = xs.map(f)
Move 2½ · endofunctor
Endo: the functor never leaves the category.
number → Array<number>
A → Promise<A>
A → Maybe<A>
objects: types · arrows: functions · F maps both — laws intact, same category
Move 3 · a new category
Now zoom out: whole functors are just dots.
dots = endofunctors
arrows = natural transformations
safeHead : Array<A> → Maybe<A> — uniformly, no special cases
Breath — the other word you already know
⊕
monoid = a way to combine two things, plus a do-nothing value. You’ve passed both to reduce() since your first week.
Move 4 · monoid
Combine, identity, two laws.
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const concat = (xs) => xs.reduce((a, b) => a + b, "");
associative: (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)
identity: e ⊕ a = a = a ⊕ e
associativity is why tree-reduction is safe for parallelism
Generalize
No elements? Multiplication becomes a morphism.
⊗ = pairing · 1 = the unit type (both exist in TS)
monoid object = M + μ + η + two laws
Assemble
Swap the set for an endofunctor.
[[1, 2], [3]].flat(); // μ · join
Array.of(1); // η · return
p.then(nextPromise); // then auto-joins
carrier set → endofunctor T
the monoid laws, re-expressed = the monad laws
Take it home
The whole dictionary.
Monoid · a set
Monad · an endofunctor
carrier set S
endofunctor T — Array, Promise, Maybe
element a ∈ S
a : T A — “a value in a context”
multiply μ(a, b)
join : T (T A) → T A
identity e
of / return : A → T A
(a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)
join ∘ join = join ∘ map join
e ⊕ a = a = a ⊕ e
join ∘ of = id = join ∘ map of
Why care: the laws are rewrite rules. map(f).map(g) fuses to map(g ∘ f). then-chains re-associate freely. Flatten in any order — same result. That guarantee is what “it’s just a monoid” buys you.
The takeaway
It’s just composition, twice.
Arrows compose in a category. Functors compose as objects. A monad is the monoid you get when that second composition has a unit.
Go deeper: B. Milewski — Category Theory for Programmers (free online) · S. Mac Lane — CWM 1971, §VI.3
1 / 13
→ / click · next step → next slide · R reset · A all · S notes