folding-over-datalisted
Install: claude install-skill yutna/functional-design-skills
# Folding Over Data
## Overview
A fold reduces a structure to a value by combining its elements with a
function. Almost every loop that builds up a result is a fold in
disguise, and rewriting it as one removes the mutable accumulator, the
index, and the off-by-one errors, leaving only the combining step, which
is the part that carries meaning.
The same operation generalises past lists. Any recursive type has a fold:
one function per case, applied bottom-up. That is what replaces the
visitor pattern and most manual tree recursion.
## When to use
- A loop with an accumulator variable
- Summing, counting, grouping, or finding a maximum
- Walking a tree, an expression, or a nested document
- Deriving current state from a list of events
- Replacing a visitor or a recursive helper with an explicit shape
Not for: transforming each element independently, which is a map; or
selecting elements, which is a filter.
## Core rules
1. **Name the accumulator type first.** What is being built determines
the fold's shape more than the elements do.
2. **The combining function is pure and total.** Same accumulator and
element, same result, no effect.
3. **Prefer the specific operation when one exists.** `sum`, `maximum`,
`groupBy` and `count` say more than a fold with a lambda.
4. **Fold from the left for accumulation, from the right to build a
structure.** Left folds are iterative and constant in stack; right
folds build lazily and suit infinite sequences.
5. **One fold p