Skip to content

Spreadsheets

These four programs come from real spreadsheets. Each program is a set of formula columns of the sheet app. The package @vex/pilots gives each program three times: with the typed builder, with the formula language, and in plain TypeScript. Property tests compare the three on random inputs.

The examples on this page use runFormulas of @vex/pilots. It compiles the formulas with @vex/formula, and it evaluates the cells with a SheetRun. A cell gives a value, or an error value with a reason.

The opening balance of a month is the closing balance of the month before. row(-1) reads the row above. At the first row, row(-1) gives #REF!, and IFERROR gives the principal.

import { runFormulas } from "@vex/pilots";
const months = space.array([{ payment: 260, extra: 0 }, { payment: 260, extra: 0 }, { payment: 260, extra: 0 }]);
const cells = runFormulas(months, ["payment", "extra"], {
opening: "= IFERROR(row(-1).closing, 1000)",
interest: "= opening * 0.01",
closing: "= opening + interest - payment - extra",
});
cells("0", "closing"); // => { ok: true, value: 750 }
cells("1", "closing"); // => { ok: true, value: 497.5 }

A schedule of 600 months found a defect in SheetRun. A first read at the last month went deep into the call stack, and the overflow became an error value. IFERROR then gave the principal, so the balance was wrong and no cell showed an error. After the fix, a read warms the column in key order (rule SHEET.RECURRENCE).

Version 0.5.0 then removed the cause. A sheet reads its cells from a work list, so a long chain does not fill the call stack (rule SHEET.DEEP). A full call stack in host code gives #DEPTH!, and IFERROR does not hide it.

A product is a tree of parts. A part has a quantity in its parent and a unit cost. SUM(children, qty * rolled) evaluates qty * rolled at each child. Each part reads its own column rolled at its children, so the cost rolls up the tree.

import { runFormulas } from "@vex/pilots";
const parts = space.tree(
{ bike: { qty: 1, cost: 100 }, wheel: { qty: 2, cost: 20 }, spoke: { qty: 32, cost: 0.25 }, tube: { qty: 1, cost: 5 }, seat: { qty: 1, cost: 15 } },
{ wheel: "bike", spoke: "wheel", tube: "wheel", seat: "bike" },
);
const cells = runFormulas(parts, ["qty", "cost"], {
rolled: "= cost + SUM(children, qty * rolled)",
need: "= IF(COUNT(ancestors) = 0, 1, qty * parent.need)",
});
cells("bike", "rolled"); // => { ok: true, value: 181 }
cells("spoke", "need"); // => { ok: true, value: 64 }

FIX(name, join, first, step) makes a column that repeats its step until no row changes, and LAST(name) reads the row in the last round. The join OR moves a row from FALSE to TRUE only, so the rounds stop. A cycle of rows is not an error here. The axes of a formula are the axes of a tree, so this column follows the ancestors of a row.

import { runFormulas } from "@vex/pilots";
const teams = space.tree(
{ north: { audited: true }, east: { audited: false }, shop: { audited: false }, west: { audited: false } },
{ east: "north", shop: "east" },
);
const cells = runFormulas(teams, ["audited"], {
covered: "= FIX(covered, OR, audited, ANY(ancestors, LAST(covered)))",
});
cells("shop", "covered"); // => { ok: true, value: true }
cells("west", "covered"); // => { ok: true, value: false }

A step must not fall when the last round rises. Thus NOT(LAST(x)) gives #VALUE!. The builder has the same column, with the method fix.

A class is a root, and its students are its children. parent.children is the class of a student. In a WHERE test, score reads at each sibling, and this.score reads at the student of the formula.

import { runFormulas } from "@vex/pilots";
const school = space.tree({ maths: {}, ada: { score: 94 }, bo: { score: 81 }, cy: { score: 81 } }, { ada: "maths", bo: "maths", cy: "maths" });
const cells = runFormulas(school, ["score"], {
mean: "= AVERAGE(parent.children.score)",
rank: "= 1 + COUNT(siblings WHERE score > this.score)",
});
cells("ada", "mean"); // => { ok: true, value: 256 / 3 }
cells("bo", "rank"); // => { ok: true, value: 2 }

An invoice is a root, and its lines are its children. A line without a price gives an error value with a reason. SUM is strict, like a spreadsheet. Thus the check of the invoice is an error value too, not a wrong TRUE or FALSE.

import { runFormulas } from "@vex/pilots";
const invoice = space.tree({ A: { total: 54, discount: 0.1 }, line1: { qty: 2, price: 10 }, line2: { qty: 4 } }, { line1: "A", line2: "A" });
const cells = runFormulas(invoice, ["qty", "price", "total", "discount"], {
lineTotal: "= qty * price",
linesSum: "= SUM(children.lineTotal)",
totalOk: "= ABS(total - linesSum * (1 - discount)) <= 0.005",
});
cells("line1", "lineTotal"); // => { ok: true, value: 20 }
cells("line2", "lineTotal"); // => { ok: false, error: { code: "#N/A", ... } }
cells("A", "totalOk"); // => { ok: false, error: { code: "#N/A", ... } }

In the sheet app, a formula column can read other formula columns at other rows, and those columns can read more columns. The reads can go up the tree, down the tree and across to the row before. Vex finds the order of the evaluation, so the order of the columns has no effect. Only a real cycle gives #CYCLE!.

The menu of the app has these ten sheets. Each link opens one of them.

Sheet How the formulas read each other
A page layout Width adds the widths of the children. X reads the X and the Width of the box before, or the X of the parent. Thus the widths go up, and the positions go down and across.
Rabbits and foxes Rabbits reads row(-1).Foxes, and Foxes reads row(-1).Rabbits. The two columns read each other, but each read goes to the row before. Thus the sheet has no cycle.
A project plan A task starts at the end of the task before it. A phase starts with its parent and ends at MAX(children.Finish).
A thrown ball The velocity and the position step together as vectors. Y(Position) gives the height, and the last row shows the ball below the ground.
Test scores A z-score has an aggregate inside an aggregate: SQRT(AVERAGE(all, (Score - AVERAGE(all.Score)) ^ 2)).
An org chart The headcount and the cost go up the tree. The level goes down the tree: IFERROR(parent.Level, 0) + 1.
Monthly sales AVERAGE(rows(-2, 0).Sales) is a moving average of three months. rows(from, to) reads a window of rows, so the total for the year is one SUM, not a chain of reads.
Invoices with dates Due is Issued + Terms, a date plus some days. Pay by moves a due date on a weekend to the Monday after it with WEEKDAY(Due). Days late is a date minus a date.
Orders and products Two tables read each other. An order reads the price of its product with SUM(table("Products") WHERE Name = this.Item, Price), and a product counts its units in the orders. Each read goes to a value column, so the tables have no cycle.
A recipe that scales The scale goes down the tree from the number of servings. The cost goes up the tree from the ingredients.

Four of the sheets read a row by its name, for example row("Launch").Start. The name of a row is the text of its first column. If you change the name, the formula gives #VALUE! with the reason. It does not read a different row.

The rabbits and foxes, the thrown ball, the loan and the monthly sales open with a chart. A column of numbers gives a line, and a column of vectors gives a path. The path of the ball has one scale on the two axes, so the arc keeps its real form. The button Chart adds a chart to any sheet, and a click on a point selects its row.

The button New grid starts a grid, like the sheet of a spreadsheet. The price list is an example. The columns have letters, the rows have numbers, and D2 reads a cell. A text that starts with = is a formula, and SUM(D2:D4) adds a range. The cells of a grid are the cells of a Vex sheet, so a cycle gives #CYCLE! as in a table.

  • SheetRun gave a wrong balance at the end of a long recurrence, without an error. Version 0.5.0 removed the cause: a sheet does not depend on the call stack.
  • The typed builder had no member for the form if. A builder program used ifError with a value that fails on purpose. Version 0.4.0 added if() to the chain.
  • A text as the left value of * gives #NAME?, because the text domain has no op multiply. A spreadsheet gives #VALUE!.