Skip to content

Recursion and folds

In lesson 3 Relay got a routing-rule tree and two functions over it, evaluate and describe. Then the admin UI asked for “how many conditions does this rule have”, the validator wanted “does it mention a header at all”, and a month later there were five functions with the same switch and the same recursive calls. One of them forgot to recurse into Not, so a rule hidden under a negation was never validated.

A fold writes the recursion once. What differs between the five functions is only what to do at each node, so that part becomes an argument.

You already use the simplest fold. reduce replaces a list by a single value, given a starting value and a step:

const sum = [1, 2, 3].reduce((acc, n) => acc + n, 0)
// It does not have to stay a number. Fold jobs into counts per source:
const sources = ["github", "stripe", "github"]
const counts = sources.reduce<Readonly<Record<string, number>>>(
(acc, s) => ({ ...acc, [s]: (acc[s] ?? 0) + 1 }),
{},
)
console.log(sum, counts)

The result type is free. The step builds a new value each time and never mutates, the same immutable update you already know. Many loops that fill an accumulator are folds.

A list has one recursive position, its tail. The rule tree has two kinds: And and Or have a list of children and Not has one. A fold over it takes one handler per case. For the branches the handler receives the children already folded, and for the leaves it receives their fields:

type Rule =
| { readonly _tag: "And"; readonly rules: readonly Rule[] }
| { readonly _tag: "Or"; readonly rules: readonly Rule[] }
| { readonly _tag: "Not"; readonly rule: Rule }
| { readonly _tag: "SourceIs"; readonly source: string }
| { readonly _tag: "HeaderEquals"; readonly name: string; readonly value: string }
interface RuleHandlers<A> {
readonly and: (results: readonly A[]) => A
readonly or: (results: readonly A[]) => A
readonly not: (result: A) => A
readonly sourceIs: (source: string) => A
readonly headerEquals: (name: string, value: string) => A
}
function foldRule<A>(handlers: RuleHandlers<A>): (rule: Rule) => A {
const go = (rule: Rule): A => {
switch (rule._tag) {
case "And":
return handlers.and(rule.rules.map(go))
case "Or":
return handlers.or(rule.rules.map(go))
case "Not":
return handlers.not(go(rule.rule))
case "SourceIs":
return handlers.sourceIs(rule.source)
case "HeaderEquals":
return handlers.headerEquals(rule.name, rule.value)
}
}
return go
}

This is called a catamorphism, and the name is the only hard part. It is the one function that knows the shape of Rule. The switch is exhaustive here and nowhere else. The handler object is exhaustive too: leaving out headerEquals is a compile error in every caller.

The two functions from lesson 3 become handler tables. Only the A changes, boolean for one, string for the other:

type Rule =
| { readonly _tag: "And"; readonly rules: readonly Rule[] }
| { readonly _tag: "Or"; readonly rules: readonly Rule[] }
| { readonly _tag: "Not"; readonly rule: Rule }
| { readonly _tag: "SourceIs"; readonly source: string }
| { readonly _tag: "HeaderEquals"; readonly name: string; readonly value: string }
interface RuleHandlers<A> {
readonly and: (results: readonly A[]) => A
readonly or: (results: readonly A[]) => A
readonly not: (result: A) => A
readonly sourceIs: (source: string) => A
readonly headerEquals: (name: string, value: string) => A
}
declare function foldRule<A>(handlers: RuleHandlers<A>): (rule: Rule) => A
interface RawWebhook {
readonly source: string
readonly headers: Readonly<Record<string, string>>
readonly body: string
}
const evaluate = (webhook: RawWebhook) =>
foldRule<boolean>({
and: (rs) => rs.every(Boolean),
or: (rs) => rs.some(Boolean),
not: (r) => !r,
sourceIs: (source) => webhook.source === source,
headerEquals: (name, value) => webhook.headers[name.toLowerCase()] === value,
})
const describe = foldRule<string>({
and: (rs) => `(${rs.join(" and ")})`,
or: (rs) => `(${rs.join(" or ")})`,
not: (r) => `not ${r}`,
sourceIs: (source) => `source = ${source}`,
headerEquals: (name, value) => `header ${name} = ${value}`,
})
declare const webhook: RawWebhook
declare const rule: Rule
console.log(evaluate(webhook)(rule), describe(rule))

No handler calls itself. Recursion has been moved out of them, so none can forget to recurse into Not. A new analysis, such as the number of leaves, is five short lines. A fold can also change the type completely: a fold to number can compute depth, and a fold to Rule can rewrite the tree, for example to push Not down to the leaves.

Honest cost: a fold computes all children before the handler runs. evaluate as a fold checks every child of an Or, where the direct version from lesson 3 stops at the first true. For a rule tree of a dozen nodes it does not matter. For an expensive leaf, write the direct recursion or make the children lazy.

Each recursive call uses a stack frame, and the stack is finite. A rule tree written by a person is a few levels deep. A chain of a hundred thousand nested Not nodes, produced by a program, is not:

type Chain = { readonly next: Chain | undefined }
function depth(chain: Chain): number {
return chain.next === undefined ? 1 : 1 + depth(chain.next)
}
// The same walk with an explicit loop: the call stack stays flat.
function depthLoop(chain: Chain): number {
let n = 0
for (let node: Chain | undefined = chain; node !== undefined; node = node.next) n++
return n
}

depth throws a RangeError on a long enough chain, and TypeScript will not warn you. When the input can be adversarial or machine generated, bound it (reject rules deeper than 50 when they are parsed, as the rest of Relay does for payload size) or use a loop with an explicit stack, an array of nodes still to visit. The loop is longer and harder to read, but it works at any depth. ES2015 specifies proper tail calls, but V8 and most engines do not implement them. Only JavaScriptCore (Safari, Bun) does, so do not rely on tail form.

Implement foldRule and express evaluate, describe and countLeaves as folds over it. The Rule type is copied from lesson 3. Then fold a list of job events into per-source stats with reduce and no mutation. The starter’s folds return fixed values.

  • reduce is a fold: the accumulator can be any type, and the step builds a new one.
  • foldRule is the only function that recurses over Rule. Handlers get already folded children.
  • evaluate, describe and counting differ only in the result type and the handlers.
  • The exhaustive switch lives in the fold, and the handler object makes every caller exhaustive.
  • Recursion uses the call stack: bound the depth of untrusted input or walk it with an explicit stack.