← ClaudeAtlas

functional-folding-over-datalisted

Use when a loop accumulates into a variable, when combining a collection into one value, when the same tree walk keeps being written again, or when a combining law matters.
yutna/functional-design-skills · ★ 0 · Data & Documents · score 75
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. Default. **Name the accumulator type first.** What is being built determines the fold's shape more than the elements do. 2. Rule. **The combining function is pure and total.** Same accumulator and element, same result, no effect. 3. Default. **Prefer the specific operation when one exists.** `sum`, `maximum`, `groupBy` and `count` say more than a fold with a lambda. 4. Default. **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 in