The previous chapter changed something, and most of the work was making that change safe to approve. This one changes nothing. It prices an invoice and splits a bill, the kind of arithmetic that has to come out right to the cent and be the same every time anyone checks it.
A calculation like this is Captain with no effects. It has no plan to approve, because there is nothing to perform. What it has instead are three promises: every number is an exact decimal, every place a digit is dropped is written in the source with its rule, and the same inputs always give the same result.
The program
module Shop::Invoice.
;; One line of an invoice: how many of an item, at what price each.
export struct Line { item: Text, quantity: i32, unitPrice: Decimal }.
;; The figures at the foot of an invoice.
export struct Totals { subtotal: Decimal, discount: Decimal, tax: Decimal, total: Decimal }.
;; A count times a price loses no digits, so nothing is rounded here.
amount line: Line -> Decimal [
ret ((line quantity) as: Decimal) * (line unitPrice).
].
;; The totals of an invoice. The discount and the tax are rounded to cents,
;; and each says how.
export totals lines: List[Line] discountPercent: Decimal taxPercent: Decimal -> Totals [
subtotal := 0.00.
lines forEach: [ :line | subtotal := subtotal + (amount line: line) ].
discount := (subtotal * discountPercent) divide: 100.0 scale: 2 rounding: #HalfEven.
taxable := subtotal - discount.
tax := (taxable * taxPercent) divide: 100.0 scale: 2 rounding: #HalfUp.
ret Totals { subtotal: subtotal, discount: discount, tax: tax, total: taxable + tax }.
].
;; A quote for one item: the same calculation, over a list of one line.
export quote item: Text quantity: i32 unitPrice: Decimal
discountPercent: Decimal taxPercent: Decimal -> Totals [
lines := List empty: Line.
lines := lines push: Line { item: item, quantity: quantity, unitPrice: unitPrice }.
ret totals lines: lines discountPercent: discountPercent taxPercent: taxPercent.
].
;; An equal share of an amount, if there is an exact one.
export share amount: Decimal among: i32 -> Decimal [
ret amount / (among as: Decimal).
].
;; Shares of an amount that add up to it exactly. Each party gets the amount
;; divided by the number of parties, rounded down to the cent, and the cents
;; left over go one each to the first parties.
export split amount: Decimal among: i32 -> Result[List[Decimal]] [
(among < 1) ifTrue: [
ret Fail { err: Err { kind: #NoParties, message: "split among one party or more" } } ].
((amount scale: 2 rounding: #Down) != amount) ifTrue: [
ret Fail { err: Err { kind: #NotCents, message: "the amount must be in whole cents" } } ].
each := amount divide: (among as: Decimal) scale: 2 rounding: #Down.
left := amount - (each * (among as: Decimal)).
shares := List empty: Decimal.
[ (shares count) < among ] whileTrue: [
extra := 0.00.
(left > 0.00) ifTrue: [
extra := 0.01.
left := left - 0.01.
].
shares := shares push: each + extra.
].
ret Ok { v: shares }.
].A few things to notice while reading it:
- Records and a list. An invoice is a
List[Line], and its result is aTotalsrecord.totalsadds the lines up withforEach:;quotebuilds a one-line list withpush:, which gives a new list rather than changing the old one (Lists and shapes). - Conversions are written. A quantity is an
i32and a price aDecimal, and Captain never mixes the two on its own.(line quantity) as: Decimalconverts the count, exactly (as:). - Rounding is written. Multiplying and adding decimals is exact, so
subtotalkeeps every digit. The two places where a result must be cut to cents, the discount and the tax, usedivide:scale:rounding:and name the scale and the mode. The rules here are only an example: the discount rounds half to even and the tax half up. Whatever your rules are, an auditor finds each one by reading the line where it happens. - Values are chosen by returning.
splitchecks its arguments withifTrue:and returns aFailearly; there is noifexpression (Blocks and control).
Check, build, inspect
$ captain check invoice.capt
ok invoice.capt (module Shop::Invoice, 7 declarations)
checked 1 file as 1 module, no errors
$ captain build invoice.capt -o invoice.capb
built invoice.capb ([..])
$ captain inspect invoice.capb
package Shop::Invoice 0.0.0
sha256 [..]
compiler 0.1.0 vm [..] stripped
exports
quote item: Text quantity: i32 unitPrice: Decimal discountPercent: Decimal taxPercent: Decimal -> Totals (pure)
share amount: Decimal among: i32 -> Decimal (pure)
split amount: Decimal among: i32 -> Result[List[Decimal]] (pure)
totals lines: List[Line] discountPercent: Decimal taxPercent: Decimal -> Totals (pure)
entry points
quote item:quantity:unitPrice:discountPercent:taxPercent: item=<Text> quantity=<i32> unitPrice=<Decimal> discountPercent=<Decimal> taxPercent=<Decimal>
share amount:among: amount=<Decimal> among=<i32>
split amount:among: amount=<Decimal> among=<i32>
pools: [..]Every export is (pure): it reaches no effect at all, which the
checker established from the source and the artifact records. There is no
effects section, because there is nothing to list.
totals is an export but not an entry point. The command line spells
scalars: numbers, text, symbols and tagged values. It has no way to write a
list of records, so captain run cannot call totals. That is why the
module also has quote, which takes scalars and makes the list itself.
A program that embeds Captain can call totals directly
(below).
Running it
A quote for three lamps at 19.99, with 10% off and tax at 8.25%:
$ captain run invoice.capb quote item=lamp quantity=3 unitPrice=19.99 \
discountPercent=10 taxPercent=8.25
run log: quote.runlog
Totals { subtotal: 59.97, discount: 6.00, tax: 4.45, total: 58.42 }The subtotal is exactly 59.97. Ten percent of it is 5.997, which the discount rounds to 6.00. The taxable amount, 53.97, at 8.25% is 4.452525, which rounds to 4.45. Nothing was approximated along the way: the only digits that were dropped are the ones the two rounding lines say.
Division says what it does
Splitting a bill three ways looks like a division. share writes it with
/, and / on decimals is exact or fails:
$ captain run invoice.capb share amount=90.00 among=3
run log: share.runlog
30.00
$ captain run invoice.capb share amount=100.00 among=3
run log: share.runlog
error[CAP-RUN-INEXACT]: 100.00 / 3 has no exact decimal quotient: `/` never drops digits. Say where the quotient is cut and how: `a divide: b scale: 2 rounding: #HalfEven`There is no exact third of 100.00, and Captain will not choose one for you.
A language that quietly gave 33.33 would leave a cent unaccounted for, and
nobody reading the source would see where it went. split does the
division as a person would: it rounds each share down to the cent, then
hands out the cents that are left, so the shares always add up to the
amount:
$ captain run invoice.capb split amount=100.00 among=3
run log: split.runlog
Ok { v: #( 33.34, 33.33, 33.33 ) }
$ captain run invoice.capb split amount=100.00 among=7
run log: split.runlog
Ok { v: #( 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ) }
$ captain run invoice.capb split amount=100.005 among=3
run log: split.runlog
Fail { err: Err { kind: #NotCents, message: "the amount must be in whole cents" } }
$ captain run invoice.capb split amount=100.00 among=0
run log: split.runlog
Fail { err: Err { kind: #NoParties, message: "split among one party or more" } }Arguments split cannot honour come back as Fail values, which a caller
can examine, rather than as a crash
(Option and Result). Without the
first check, among=0 would stop the run with a division by zero; without
the second, an amount with a fraction of a cent would leave that fraction
in no one's share.
Division and rounding covers
/, divide:scale:rounding: and the seven rounding modes, and
Quantities and money the
Money type, which carries its currency with the amount.
The same inputs, the same result
A pure calculation's result depends on its arguments and nothing else: there is no clock, no randomness, no locale and no floating point to differ from one machine to the next. Its plan says so:
$ captain plan invoice.capb split amount=100.00 among=7
...
no effects: the entry is pure at these arguments
...
result: Ok { v: #( 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ) }
...Run it twice and the run logs are byte for byte the same. The log holds the artifact, the entry, a digest of the arguments and the result, and no effect lines, because there were none:
$ captain run invoice.capb split amount=100.00 among=7 --log first.runlog
run log: first.runlog
Ok { v: #( 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ) }
$ captain run invoice.capb split amount=100.00 among=7 --log second.runlog
run log: second.runlog
Ok { v: #( 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ) }
$ cmp first.runlog second.runlog && echo identical
identical
$ cat first.runlog
capb [..]
vm [..]
entry split amount:among:
args [..]
status completed Ok { v: #( 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ) }
$ captain replay invoice.capb first.runlog amount=100.00 among=7
replay ok: Ok { v: #( 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ) }
$ captain replay invoice.capb first.runlog amount=100.00 among=6
CAP-REPLAY-DIVERGENCE: run arguments differ from the recorded runAnyone who holds the artifact and the arguments can recompute the result later, anywhere, and get the same one. Builds are deterministic too, so the artifact can itself be checked against its source by building it again (Determinism, run records and replay).
From your own program
An invoice comes from somewhere: a form, an order system, a file. The
program that holds it passes it to Captain through the Rust SDK,
captain-sdk, rather than through a command line. The SDK can call
totals directly, because it can pass what the command line cannot: a
List[Line] whose items are Line records. Each record is checked against
the struct exactly, with every field given once and nothing coerced, so an
item that is missing or a quantity given as a decimal is refused before
the calculation starts. The result comes back as a Totals record with its
field names.
For a pure entry, the SDK also gives a run record: a short text that binds the artifact, the entry, the arguments, the limits and the result, and can be verified later by running again and comparing. That is the evidence an auditor keeps.
Embedding Captain in Rust shows all of it: the pure profile, with an order total much like this one, values in and out, and run records.