Page: one entry changes a balance by a fixed amount

Job: explanation

Level: mid grug (level 2 of 6)

Source lines:

  • src/Apply.fs:5#apply
  • src/Replay.fs:5#replay

one entry changes a balance by a fixed amount

mid grug (level 2 of 6)explanationteaches: apply-is-addition, fold-carries-the-entry

explanation

this page says why the code has this shape and what a reader must be careful of.

why this exists

A ledger entry is one integer added to a balance. apply is that whole operation. src/Apply.fs:5#apply is the line to open and change. src/Replay.fs:5#replay calls it once for every entry.

source anchor: this line is in the file

run sed -n '5,9p' src/Apply.fs

It prints:

let apply (balance: int) (delta: int) =
  balance + delta
/// The identity entry leaves the balance alone.
let zero = 0

The cited file src/Apply.fs ships with this site at the same path. Run the command from the school folder, or open src/Apply.fs.

what breaks

Change + to - and a credit becomes a debit. The balance still prints, so a reader who checks only the shape of the output misses the fault.

where it fits

replay uses the same addition for every entry, at src/Replay.fs:5#replay. The oracle is the answer a correct run must match.

try it

Run grep -n 'let apply' src/Apply.fs from this folder. Then change + to - in src/Apply.fs and run grugschool check .. The proof on this page goes red under the callout.

reference: every connection to this page
where this fits

This is reference. The next page in the reading order is at the bottom of the page.

goes on to: replay is one fold over the entries

flowchart LR
  H["you are here: one entry changes a balance by a fixed amount"]
  B0["replay is one fold over the entries"]
  H --> B0

grill: say it out loud, then tap

Grug asks. Say the answer out loud, then tap. Grug remembers what you miss and asks again in the pop quiz.

a badge says two things: the number is its level, the colour is the kind of answer it asks for. The six levels are level 1 of 6 recall a fact; level 2 of 6 recall a detail; level 3 of 6 trace a path; level 4 of 6 trace a longer path; level 5 of 6 predict or judge; level 6 of 6 judge a transfer. Colour and level are independent: a high-level question can still ask for a fact, and the colour tells you which it is.

level 2 of 6Q1 · What does apply do to the balance for one entry?
try first, then show answer

4. It adds the delta to the balance

why

apply has one operation: balance + delta. A credit adds; a debit is a negative delta.

level 3 of 6Q2 · Where does a wrong sign in apply reach the replayed balance?
try first, then show answer

2. In every step of the fold, because replay calls apply for each entry

why

replay folds over the entries with the same addition, so a wrong sign in apply changes every step. The closed-form oracle uses List.sum, which stays correct when the implementation changes.