Functional Weave
Code in TypeScript

agri.gross-margin

Enterprise gross margin (output less variable costs), in total and per hectare or per head, in exact money.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 14 tests, run in TypeScript, Python and Rust.

What it does

The gross margin of a farm enterprise (a crop, a flock, a herd): its output less the variable costs that rise and fall with it, in total and per hectare or per head, with the margin as a share of output. Fixed costs (labour, machinery depreciation, rent, overheads) are deliberately not in it; that is what makes gross margins comparable between farms and against the published benchmarks.

`grossMargin(outputs, variableCosts, "hectare", 100, "GBP")` for 100 ha of wheat with £238,000 output and £52,000 variable costs is a £186,000 margin, £1,860 per hectare, 78.15% of output.

For example

  • grossMargin(outputs ×2, variable costs ×4, hectare, 100, GBP) → output £238,000.00, variable costs £52,000.00, gross margin £186,000.00, output per unit £2,380.00, variable costs per unit £520.00, gross margin per unit £1,860.00, margin basis … 100 ha of winter wheat: grain and straw less seed, fertiliser, sprays and sundries
  • grossMargin(outputs ×2, variable costs ×3, head, 500, GBP) → output £50,500.00, variable costs £17,500.00, gross margin £33,000.00, output per unit £101.00, variable costs per unit £35.00, gross margin per unit £66.00, margin basis points 6… a 500-ewe flock per ewe
  • grossMargin(outputs ×1, variable costs ×1, head, 3, GBP) → output £100.00, variable costs £50.00, gross margin £50.00, output per unit £33.33, variable costs per unit £16.67, gross margin per unit £16.67, margin basis points 50% the margin per head is the margin divided once (1667), not output per head less costs per head (1666)

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function grossMargin(outputs: readonly MarginLine[], variableCosts: readonly MarginLine[], per: MarginBasis, units: number, currency: string): GrossMargin
outputsMarginLine[]sales, subsidies tied to the enterprise, valuation change; may be empty
variableCostsMarginLine[]seed, fertiliser, sprays, feed, vet, contract work; not fixed costs
perMarginBasishectare or head
unitsfloathectares (taken to 0.0001 ha) or head (a whole number), more than zero
currencystringevery amount must be in it
returnsGrossMargin

The types it declares, generated into your project

export type MarginBasis = "hectare" | "head";

/** One named output or cost. */
export interface MarginLine {
  readonly name: string;
  readonly amount: Money;
}

/** Totals and the same per hectare or head, each divided once from its total. */
export interface GrossMargin {
  readonly output: Money;
  readonly variableCosts: Money;
  readonly grossMargin: Money;
  readonly outputPerUnit: Money;
  readonly variableCostsPerUnit: Money;
  /** total margin / units, not output per unit less costs per unit */
  readonly grossMarginPerUnit: Money;
  /** gross margin as a share of output, 10000 = 100%; null when output is zero */
  readonly marginBasisPoints: number | null;
}

Your code names it in one line, in the file that uses it

import { grossMargin } from "#fune/agri.gross-margin@^1";
impl/typescript.ts · 60 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { type Money, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { sumMoney } from "./money_sum.ts";  ← from money.sum ^1.0.0 · built alongside by fune
import { subtractMoney } from "./money_add.ts";  ← from money.add ^1.0.0 · built alongside by fune
import { roundDiv } from "./math_round_div.ts";  ← from math.round-div ^1.0.0 · built alongside by fune
import { type GrossMargin, type MarginBasis, type MarginLine } from "./agri_gross_margin_types.ts";

const MAX_MINOR = 900000000000;

/**
 * Gross margin: enterprise output less its variable costs, per hectare or head.
 *
 * Each per-unit figure is its own total divided once, half up. Taking output
 * per head less costs per head instead can be a penny out: 3 head with 10000
 * output and 5000 costs is 3333 - 1667 = 1666 that way, but 5000 / 3 = 1667.
 */
export function grossMargin(
  outputs: readonly MarginLine[],
  variableCosts: readonly MarginLine[],
  per: MarginBasis,
  units: number,
  currency: string,
): GrossMargin {
  let divisor: number;
  let scale: number;
  if (per === "hectare") {
    if (typeof units !== "number" || !Number.isFinite(units) || units <= 0 || units > 10000000) {
      throw new RangeError(`units must be a finite number of hectares greater than 0 and at most 10000000, received ${units}`);
    }
    divisor = Math.round(units * 10000);
    if (divisor < 1) throw new RangeError(`units must be at least 0.0001 hectares, received ${units}`);
    scale = 10000;
  } else if (per === "head") {
    if (typeof units !== "number" || !Number.isInteger(units) || units < 1 || units > 10000000) {
      throw new RangeError(`units must be a whole number of head from 1 to 10000000, received ${units}`);
    }
    divisor = units;
    scale = 1;
  } else {
    throw new RangeError(`unknown basis "${per}": use hectare or head`);
  }

  const output = sumMoney(outputs.map((line) => line.amount), currency);
  const costs = sumMoney(variableCosts.map((line) => line.amount), currency);
  const margin = subtractMoney(output, costs);
  for (const m of [output, costs, margin]) {
    if (Math.abs(m.minor) > MAX_MINOR) {
      throw new RangeError("totals must be within 900000000000 minor units either side of zero");
    }
  }
  const perUnit = (m: Money): Money => money(roundDiv(m.minor * scale, divisor, "half-up"), currency);
  return {
    output,
    variableCosts: costs,
    grossMargin: margin,
    outputPerUnit: perUnit(output),
    variableCostsPerUnit: perUnit(costs),
    grossMarginPerUnit: perUnit(margin),
    marginBasisPoints: output.minor === 0 ? null : roundDiv(margin.minor * 10000, output.minor, "half-up"),
  };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add agri.gross-margin
Download for TypeScript agri.gross-margin-1.0.0-typescript.fune · 20,495 bytes sha256 38cf9958a729313d24cf70b97586c3caa40cf2ac8e79fb7c1d4273bf578c3fce

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./agri.gross-margin-1.0.0-typescript.fune, or fetch it from a terminal with fune pull agri.gross-margin@1.0.0:typescript.

The whole function, every language, is one file too: agri.gross-margin-1.0.0.fune, 27,146 bytes, sha256 01046e119ccab8b1635dcb534ab490eacc1e7554bb76ec17a2b96641c60934b3. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before agri.gross-margin

after — your function gets the result and the arguments, and returns the final result.

// fune: after agri.gross-margin

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace math.round-div in agri.gross-margin
// fune: replace money.add in agri.gross-margin
// fune: replace money.amount in agri.gross-margin
// fune: replace money.sum in agri.gross-margin

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show agri.gross-margin --steps.

// fune: step agri.gross-margin after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
100 ha of winter wheat: grain and straw less seed, fertiliser, sprays and sundries outputs ×2, variable costs ×4, hectare, 100, GBP → output £238,000.00, variable costs £52,000.00, gross margin £186,000.00, output per unit £2,380.00, variable costs per unit £520.00, gross margin per unit £1,860.00, margin basis …
a 500-ewe flock per ewe outputs ×2, variable costs ×3, head, 500, GBP → output £50,500.00, variable costs £17,500.00, gross margin £33,000.00, output per unit £101.00, variable costs per unit £35.00, gross margin per unit £66.00, margin basis points 6…
the margin per head is the margin divided once (1667), not output per head less costs per head (1666) outputs ×1, variable costs ×1, head, 3, GBP → output £100.00, variable costs £50.00, gross margin £50.00, output per unit £33.33, variable costs per unit £16.67, gross margin per unit £16.67, margin basis points 50%
a loss-making enterprise has a negative margin outputs ×1, variable costs ×1, hectare, 10, GBP → output £1,000.00, variable costs £1,500.00, gross margin -£500.00, output per unit £100.00, variable costs per unit £150.00, gross margin per unit -£50.00, margin basis points…
no output: margin share is null and a negative half penny rounds away from zero , variable costs ×1, hectare, 2, GBP → output £0.00, variable costs £0.05, gross margin -£0.05, output per unit £0.00, variable costs per unit £0.03, gross margin per unit -£0.03, margin basis points —
a part hectare area outputs ×1, variable costs ×1, hectare, 12.5, GBP → output £12,500.00, variable costs £2,500.00, gross margin £10,000.00, output per unit £1,000.00, variable costs per unit £200.00, gross margin per unit £800.00, margin basis point…
a negative output line (a clawback) reduces output outputs ×2, variable costs ×1, head, 10, GBP → output £19,000.00, variable costs £9,000.00, gross margin £10,000.00, output per unit £1,900.00, variable costs per unit £900.00, gross margin per unit £1,000.00, margin basis poi…
no lines at all is zero everywhere , , head, 1, EUR → output €0.00, variable costs €0.00, gross margin €0.00, output per unit €0.00, variable costs per unit €0.00, gross margin per unit €0.00, margin basis points —
a fractional head count is an error outputs ×1, , head, 2.5, GBP → error: units must be a whole number of head from 1 to 10000000
zero hectares is an error outputs ×1, , hectare, 0, GBP → error: units must be a finite number of hectares greater than 0
Show the other 4 tests
CaseArgumentsExpected
less than a square metre is an error outputs ×1, , hectare, 0, GBP → error: units must be at least 0.0001 hectares
an unknown basis is an error outputs ×1, , acre, 1, GBP → error: unknown basis "acre"
a cost in another currency is an error outputs ×1, variable costs ×1, head, 1, GBP → error: currency mismatch
totals beyond 900 billion minor units are refused outputs ×1, , head, 1, GBP → error: totals must be within 900000000000 minor units

More from the author

## How it is worked out

1. Outputs and variable costs are totalled exactly in minor units (`money.sum`); every line must be in `currency`. Lines may be negative (a clawback, a credit note). 2. The margin is output less variable costs, and may be negative. 3. Each per-unit figure is its own total divided once by the hectares or head, half up (away from zero for negatives, `math.round-div`). So the per-head margin is not always per-head output less per-head costs: with 3 head, 10000 output and 5000 costs, that shortcut gives 3333 - 1667 = 1666, where 5000 / 3 is 1667. 4. `marginBasisPoints` is the margin over output, half up, and null when output is zero.

Hectares are taken to 0.0001 ha (1 m²); head is a whole number.

## What it does not do

It does not decide what is a variable cost, value stock or home-grown feed, or split shared costs between enterprises: the caller brings the lines. It is arithmetic, not an assessment of the enterprise.

## Limits

More than 0 and at most 10,000,000 hectares or head; each total within ±900,000,000,000 minor units, which keeps every intermediate below 2^53 so that TypeScript stays exact.

## Source

The definition (enterprise output less variable costs, before fixed costs) is the standard one in UK farm management, e.g. the John Nix Farm Management Pocketbook and AHDB's Farmbench costings.

Files

PathBytes
README.md1,978
impl/python.py2,638
impl/rust.rs3,776
impl/typescript.ts2,467
vectors.json11,004