// m07 io: effects as values. An IO is a plain-data description of a program; nothing runs until interpreted. // {tag:'Pure', value} - done, with a value // {tag:'Effect', op, k} - perform `op`, then continue with `k(result)` export const pure = (value) => ({ tag: 'Pure', value }) export const effect = (op) => ({ tag: 'Effect', op, k: pure }) // Pure: apply f now. Effect: keep the op, and extend the continuation so f runs after k. // Nothing is performed here, we only build a bigger description. export const flatMap = (io, f) => io.tag === 'Pure' ? f(io.value) : { tag: 'Effect', op: io.op, k: (result) => flatMap(io.k(result), f) } export const map = (io, f) => flatMap(io, (a) => pure(f(a))) export const sequence = (ios) => ios.reduceRight((rest, io) => flatMap(io, () => rest), pure(undefined)) export const draw = (shape) => effect({ tag: 'Draw', shape }) export const randomSeed = effect({ tag: 'RandomSeed' }) export const drawScene = (scene) => sequence(scene.map(draw)) // Answer each op with a canned result, collecting the ops as we go (recursion, no mutation). const answer = (op, seed) => (op.tag === 'RandomSeed' ? seed : undefined) export const trace = (io, seed) => { if (io.tag === 'Pure') return { result: io.value, ops: [] } const rest = trace(io.k(answer(io.op, seed)), seed) return { result: rest.result, ops: [io.op, ...rest.ops] } }