Laziness
Relay computes its retry plan before any job fails. The first version built an array of the next ten delays for every job, even though 99% of jobs succeed on the first attempt. The dashboard had the same habit: it parsed a day of events into objects, and then showed the last twenty.
Both are work done too early. This lesson is about doing work late, or never: values that are computed when someone asks, and sequences that produce items only as fast as they are read. The payoff is that a plan can be infinite, because nobody reads all of it.
A thunk is a delayed value
Section titled “A thunk is a delayed value”A thunk is a function with no parameters that returns the value: () => A. Passing the thunk
instead of the value lets the receiver decide whether the work happens.
declare function loadSigningKeys(): Map<string, string>
// Eager: the keys are read at startup, even for a run that never verifies a signature.const eager = loadSigningKeys()
// Lazy: nothing is read yet.const lazyKeys = () => loadSigningKeys()
function verify(source: string, keys: () => Map<string, string>): boolean { if (source === "internal") return true // keys() is never called for internal sources return keys().has(source)}
verify("internal", lazyKeys)||, && and ?? already work this way: the right side runs only if it is needed. A thunk gives
a function the same power over an argument.
Memoize it: lazy
Section titled “Memoize it: lazy”A thunk called three times does the work three times. lazy wraps a thunk so that the first call
computes and every later call returns the same result:
const lazy = <A>(thunk: () => A): (() => A) => { let state: { readonly value: A } | undefined return () => { if (state === undefined) state = { value: thunk() } return state.value }}
declare function parseRoutingTable(): ReadonlyMap<string, string>
const routes = lazy(parseRoutingTable)routes() // parsesroutes() // same Map, no parsingThe state is a one-field wrapper on purpose. A thunk that returns undefined is still a computed
value, and a bare let value: A | undefined could not tell the two apart. If the thunk throws,
state is not set, so the next call tries again. Caching a failure forever is a worse default.
The mutable state is hidden inside the closure. From outside, routes is a function that always
gives the same answer, which is all lesson 1 asks of a pure function.
Lazy iterables
Section titled “Lazy iterables”An array holds every item. An iterable gives them one at a time. A generator (M3 lesson 8)
is an iterable that runs only when asked for the next item, so map, filter and take written
as generators do no work until something reads the result:
const map = <A, B>(f: (a: A) => B) => function* (xs: Iterable<A>): Generator<B, void, unknown> { for (const x of xs) yield f(x) }
const filter = <A>(pred: (a: A) => boolean) => function* (xs: Iterable<A>): Generator<A, void, unknown> { for (const x of xs) if (pred(x)) yield x }
const take = <A>(n: number) => function* (xs: Iterable<A>): Generator<A, void, unknown> { if (n <= 0) return let seen = 0 for (const x of xs) { yield x if (++seen >= n) return } }
interface JobEvent { readonly source: string readonly ms: number}declare const events: Iterable<JobEvent>
const fromGithub = filter((e: JobEvent) => e.source === "github")(events)const durations = map((e: JobEvent) => e.ms)(fromGithub)const slowest = take<number>(20)(durations)They are curried and data-last, so they fit pipe. Reading slowest pulls events
one by one through all three steps. No intermediate array exists, and after the twentieth match the
source is not touched again.
Look at where take checks its count. It returns right after yielding the n-th item. If it checked
at the top of the loop, it would pull an extra item from the source to find out it was done, and
that item could be a database row or a network page.
Infinite sequences
Section titled “Infinite sequences”A lazy sequence may have no end. Relay’s retry schedule is “wait 100 ms, then 200, then 400 …” and the rule that stops it lives somewhere else (a retry limit, a deadline). The schedule itself does not need to know:
function* backoffSchedule(baseMs: number, factor = 2): Generator<number, never, unknown> { let delay = baseMs while (true) { yield delay delay *= factor }}
const it = backoffSchedule(100)it.next().value // 100it.next().value // 200it.next().value // 400The return type never says the generator never finishes. To get a plan, cut the sequence with
take, and cap each delay with a map step:
declare function backoffSchedule(baseMs: number, factor?: number): Generator<number, never, unknown>declare function take<A>(n: number): (xs: Iterable<A>) => Generator<A, void, unknown>declare function map<A, B>(f: (a: A) => B): (xs: Iterable<A>) => Generator<B, void, unknown>
const capAt = (maxMs: number) => map((ms: number) => Math.min(ms, maxMs))
const plan = [...take<number>(6)(capAt(1000)(backoffSchedule(100)))]// [100, 200, 400, 800, 1000, 1000]Never spread, loop over or Array.from an infinite iterable without a take in front. The
program will not throw. It will run until memory is gone. Tests that touch infinite sequences
should read through a hard cap for the same reason.
Exercise
Section titled “Exercise”The starter has lazy, map, filter, take and backoffSchedule stubbed so they compile and
do the wrong thing. Implement them. The tests count how many times work actually ran, and read
infinite sequences only through a hard cap, so a mistake fails fast.
- A thunk
() => Adelays a value. The receiver decides whether to pay for it. lazymemoizes a thunk: computed on first use, cached after, retried if it threw.- Generators make lazy
map,filterandtake. Nothing runs until the result is read, andtake(n)pulls exactly n items. - An infinite sequence is fine as long as every reader is bounded. Cut it with
takebefore spreading it. - Do not be lazy for small data or when timing and failure location matter more than the saved work.
Further reading
Section titled “Further reading”- Iteration protocols: iterables, iterators and on-demand values.
- Generator.prototype.return(): early exit and
finallyblocks.