Captain / Documentation / Part 5. Numbers

Quantities and money

Contents ↓

A quantity is an exact decimal with a unit: 30s, 1.5GiB, 85%, 19.99EUR. The unit belongs to a dimension, and the dimension is the quantity's type, so the checker can tell a timeout from a disk size and refuse to add them. Symbols, quantities and tagged values introduces the literals and the basic rules. This chapter goes further: how a quantity is stored and shown, money and currencies, rates, rounding, and quantities on the command line.

Dimensions, units and base units

Type Units Base unit
Duration ns, us, ms, s, min, h, d the nanosecond
Bytes B, KB, MB, GB, TB, KiB, MiB, GiB, TiB the byte
Percent % the percent
Money a three-letter upper-case currency code: USD, EUR, ... the currency itself

KB, MB, GB and TB are powers of 1000; KiB, MiB, GiB and TiB are powers of 1024. A d is 24 hours.

A quantity's magnitude is an exact decimal held in its dimension's base unit. 2min is held as 120,000,000,000 nanoseconds, and 1.5GiB as 1,610,612,736 bytes. Converting between units is never rounding: every unit is a whole number of base units, so 1min = 60s and 1d = 24h are simply true. All the rules of Exact decimals apply to the magnitude: it is exact, it has a scale, and it overflows with CAP-RUN-ARITH rather than wrapping.

The quantity also remembers a unit to be shown in, which is the unit it was written in. A sum or a difference keeps the unit of its left-hand side.

Arithmetic

Written Takes Gives
a + b, a - b two quantities of the same dimension that dimension
q * n, n * q a quantity and an i32, i64 or Decimal the quantity's dimension
q / n a quantity and an i32, i64 or Decimal the quantity's dimension, exact or CAP-RUN-INEXACT
a < b, a = b, ... two quantities of the same dimension bool
disks.capt
module Example::Disks.

export free size: Bytes used: Bytes -> Bytes [ ret size - used. ].

export fits size: Bytes used: Bytes -> bool [ ret used <= size. ].

export grown -> Bytes [ ret 1.5GiB + 512MiB. ].

export grownSmall -> Bytes [ ret 512MiB + 1.5GiB. ].

export decimalKilo -> bool [ ret 1KB < 1KiB. ].

export day -> bool [ ret 1d = 24h. ].

export spare -> Percent [ ret 100% - 85%. ].
Terminal
$ captain build disks.capt -o disks.capb
built disks.capb ([..] bytes, sha256 [..])
$ captain run disks.capb free size=500GiB used=120GiB
run log: free.runlog
380GiB
$ captain run disks.capb free size=500GiB used=600GiB
run log: free.runlog
-100GiB
$ captain run disks.capb fits size=500GiB used=120GiB
run log: fits.runlog
true
$ captain run disks.capb grown
run log: grown.runlog
2.0GiB
$ captain run disks.capb grownSmall
run log: grownSmall.runlog
2048.0MiB
$ captain run disks.capb decimalKilo
run log: decimalKilo.runlog
true
$ captain run disks.capb day
run log: day.runlog
true
$ captain run disks.capb spare
run log: spare.runlog
15%

grown and grownSmall are the same amount, shown in the unit of their left-hand side, with the scale of 1.5GiB. A quantity can be negative, as the second free shows; a program that must not go below zero compares first.

A quantity times a quantity has no dimension, so it is refused, and so is a quantity divided by a quantity:

Refused by the checker: CAP-TYPE-011
module Example::Ratio.

export perHalfHour -> Duration [
  ret 1h / 30min.
].

There are no compound dimensions, such as bytes per second, and no dimensionless ratio of two quantities. A plain number divided by a quantity, 2 / 5min, is refused too (CAP-TYPE-015).

Division is exact or fails

/ on a quantity follows the rule for decimals (Division and rounding): the quotient is exact, at the smallest scale that holds it and is at least the quantity's own scale, or the run stops with CAP-RUN-INEXACT. Because the magnitude is in base units, a duration divides very finely: 5min / 2 is 150 seconds, and 1ns / 2 is 0.5ns. 100USD / 3 has no exact answer, and fails.

A ladder of timeouts

Quantities make retry and timeout code read as what it means:

ladder.capt
module Example::Ladder.

;; A timeout ladder: each wait twice the one before, never more than a minute.
export ladder first: Duration steps: i32 -> List[Duration] [
  out := List empty: Duration.
  wait := first.
  i := 0.
  [ i < steps ] whileTrue: [
    out := out push: wait.
    wait := wait * 2.
    (wait > 1min) ifTrue: [ wait := 1min ].
    i := i + 1.
  ].
  ret out.
].

;; How long the whole ladder waits.
export patience first: Duration steps: i32 -> Duration [
  sum := 0s.
  (ladder first: first steps: steps) forEach: [ :w | sum := sum + w ].
  ret sum.
].
Terminal
$ captain build ladder.capt -o ladder.capb
built ladder.capb ([..] bytes, sha256 [..])
$ captain run ladder.capb ladder first=5s steps=6
run log: ladder.runlog
#( 5s, 10s, 20s, 40s, 1min, 1min )
$ captain run ladder.capb patience first=5s steps=6
run log: patience.runlog
195s
$ captain run ladder.capb ladder first=1.5s steps=3
run log: ladder.runlog
#( 1.5s, 3.0s, 6.0s )

How a quantity is shown

Text from:, and captain run when it prints a result, write a quantity in the unit it remembers, when the amount can be written in that unit with the decimal places the value carries. When it cannot, they write the raw magnitude in base units, as a mantissa and a scale, followed by the remembered unit's name and (base units):

render.capt
module Example::Render.

export half -> Duration [ ret 5min / 2. ].

export halfText -> Text [ ret Text from: (5min / 2). ].

export halfInSeconds -> Duration [ ret 300s / 2. ].

export halfWithAPlace -> Duration [ ret 5.0min / 2. ].

export overshoot -> Duration [ ret 1min - 90s. ].

export quarterKib -> Bytes [ ret 1KiB / 4. ].
Terminal
$ captain build render.capt -o render.capb
built render.capb ([..] bytes, sha256 [..])
$ captain run render.capb half
run log: half.runlog
150000000000×10⁻0min (base units)
$ captain run render.capb halfText
run log: halfText.runlog
"150000000000×10⁻0min (base units)"
$ captain run render.capb halfInSeconds
run log: halfInSeconds.runlog
150s
$ captain run render.capb halfWithAPlace
run log: halfWithAPlace.runlog
2.5min
$ captain run render.capb overshoot
run log: overshoot.runlog
-30000000000×10⁻0min (base units)
$ captain run render.capb quarterKib
run log: quarterKib.runlog
256×10⁻0KiB (base units)

Read 150000000000×10⁻0min (base units) as 150,000,000,000 nanoseconds, that is 150 seconds. The value is right; only its text is awkward, and the unit name printed after it is the remembered unit, not the unit the number is counted in. Two minutes and a half cannot be written in whole minutes, and 5min / 2 has scale 0, because 5min has. 5.0min / 2 has a decimal place to spare, so it shows as 2.5min; 300s / 2 stays in seconds.

So when a quantity will be shown to people, write the left-hand side in a unit that the results divide into, or with the decimal places the results need. Changing this rendering would change what Text from: gives for existing programs, so it is left as it is for now (DR-0034, "Not decided here").

Money and currencies

Money is a quantity whose unit is a currency, written as its ISO 4217 code. Its base unit is the currency itself, so a money amount is simply a decimal with a currency: 19.99EUR is 1999 at scale 2, in euros, and it is shown as written.

Money adds one rule: both sides of +, - or a comparison must be in the same currency. Captain does not convert currencies, because a rate of exchange is data, with a date and a source, not a constant of the language. When both amounts are written in the source, the checker knows their currencies and refuses 10USD + 5EUR (CAP-TYPE-011). Otherwise the check happens when the program runs, and a mismatch stops the run with CAP-RUN-CURRENCY.

Percentages and money do not multiply: bill * 15% is a quantity times a quantity, and is refused with CAP-TYPE-011. A percentage applied to an amount is written as a decimal fraction, bill * 0.15.

money.capt
module Example::Money.

export lineTotal price: Money units: i32 -> Money [
  ret price * units.
].

;; Net plus tax at 20%, the tax rounded half up to the cent.
export withTax net: Money -> Money [
  ret net + ((net * 0.20) scale: 2 rounding: #HalfUp).
].

;; The tax, unrounded.
export tax net: Money -> Money [ ret net * 0.20. ].

export quarters -> Money [ ret 10.00USD / 4. ].

export thirds -> Money [ ret 100USD / 3. ].

export over limit: Money -> bool [ ret 250EUR > limit. ].
Terminal
$ captain build money.capt -o money.capb
built money.capb ([..] bytes, sha256 [..])
$ captain run money.capb lineTotal price=19.99EUR units=3
run log: lineTotal.runlog
59.97EUR
$ captain run money.capb lineTotal price=19.99USD units=3
run log: lineTotal.runlog
59.97USD
$ captain run money.capb tax net=59.97EUR
run log: tax.runlog
11.9940EUR
$ captain run money.capb withTax net=59.97EUR
run log: withTax.runlog
71.96EUR
$ captain run money.capb quarters
run log: quarters.runlog
2.50USD
$ captain run money.capb thirds
run log: thirds.runlog
error[CAP-RUN-INEXACT]: 100USD / 3 has no exact decimal quotient: `/` never drops digits. Say where the quotient is cut and how: `a divide: b scale: 2 rounding: #HalfEven`
$ captain run money.capb over limit=200EUR
run log: over.runlog
true
$ captain run money.capb over limit=200USD
run log: over.runlog
error[CAP-RUN-CURRENCY]: currency mismatch: EUR vs USD

The type is Money whatever the currency, so lineTotal price:units: works for euros and dollars alike, and the currency travels with the amount. Only bringing two currencies together fails.

Rates

m per: #period makes a Rate: an amount of money per period, such as a monthly budget. The period is any symbol; the checker does not limit which. A Rate is a pair, an amount and a period, not one magnitude.

rates.capt
module Example::Rates.

;; A yearly budget as a monthly rate. `/` is exact: 1200 divides by 12.
export budget -> Rate [ ret (1200EUR / 12) per: #month. ].
Terminal
$ captain build rates.capt -o rates.capb
built rates.capb ([..] bytes, sha256 [..])
$ captain run rates.capb budget
run log: budget.runlog
100EUR per #month

Today a rate can be made, passed, returned and shown, and nothing more. The checker refuses every operator on a rate, comparison and equality included (CAP-TYPE-011):

Refused by the checker: CAP-TYPE-011
module Example::Cheaper.

export cheaper -> bool [ ret (250EUR per: #month) < (300EUR per: #month). ].

Compare and calculate with the money amounts before making them rates. A Rate has no scale:rounding:: round the amount first.

Rounding quantities

q scale: n rounding: #Mode and q divide: x scale: n rounding: #Mode work on Duration, Bytes, Percent and Money, exactly as they do on decimals (Division and rounding). The divisor x is an i32, an i64 or a Decimal. The result has the same dimension and remembers the same unit.

The scale counts decimal places of the base unit: of the currency for money, of the percent for percentages, of the byte for sizes, and of the nanosecond for durations.

rounding.capt
module Example::Rounding.

export cents -> Money [ ret 12.345USD scale: 2 rounding: #HalfEven. ].

export thirds -> Money [ ret 100USD divide: 3 scale: 2 rounding: #HalfEven. ].

export wholeNanos -> Duration [ ret 2.5ns scale: 0 rounding: #HalfEven. ].

export wholeBytes -> Bytes [ ret 1KiB divide: 3 scale: 0 rounding: #Ceiling. ].

export seconds -> Duration [ ret 1.5s scale: 0 rounding: #HalfEven. ].
Terminal
$ captain build rounding.capt -o rounding.capb
built rounding.capb ([..] bytes, sha256 [..])
$ captain run rounding.capb cents
run log: cents.runlog
12.34USD
$ captain run rounding.capb thirds
run log: thirds.runlog
33.33USD
$ captain run rounding.capb wholeNanos
run log: wholeNanos.runlog
2ns
$ captain run rounding.capb wholeBytes
run log: wholeBytes.runlog
342×10⁻0KiB (base units)
$ captain run rounding.capb seconds
run log: seconds.runlog
1500000000×10⁻0s (base units)

For money, rounding at the base unit is what is wanted: scale 2 is cents, for a currency with cents. For durations and sizes it is a fine instrument. 1KiB divide: 3 scale: 0 rounding: #Ceiling is 342 whole bytes, shown in base units because it is not a whole number of KiB. And 1.5s scale: 0 is not "1.5 seconds to whole seconds": it rounds to whole nanoseconds, which 1.5 seconds already is, and the result is shown in base units, as 1,500,000,000 nanoseconds. Rounding a duration to whole seconds or minutes, or a size to whole MiB, is not something Captain can say yet.

Quantities on the command line

A quantity argument is written as a literal is: first=5s, size=500GiB, net=59.97EUR. A number without a unit is refused.

The unit must be one that appears in the program. captain run reads a quantity argument with the artifact's own table of units, and that table holds the units the program's source writes. The ladder program above writes 1min and 0s, so it takes seconds and minutes, but not milliseconds; the disks program writes GiB, MiB, KB and KiB, but not TiB:

Terminal
$ captain run ladder.capb ladder first=500ms steps=3
error: argument `first`: unit `ms` (Duration) does not appear in this artifact
$ captain run ladder.capb ladder first=5 steps=3
error: argument `first`: `5` has no unit (expected e.g. `30s`, `8GiB`)
$ captain run disks.capb free size=1TiB used=1GiB
error: argument `size`: unit `TiB` (Bytes) does not appear in this artifact
$ captain run money.capb over limit=200GBP
error: argument `limit`: unit `GBP` (Money) does not appear in this artifact

The same holds for currencies: a program accepts amounts in the currencies it writes somewhere, and no others. A host embedding Captain meets the same rule through the SDK, which takes a quantity in a unit the artifact knows and returns its magnitude in base units (Values in and out).

Not decided yet

  • Rounding to a coarser unit: a duration to whole minutes, a size to whole MiB. The scale counts places of the base unit only. A form that names the unit waits for real use.
  • How a quantity that is not a whole number of its unit is shown, as described above.
  • Comparing and calculating with rates.
  • Points in time and calendar dates. Duration measures an interval; Instant and Date are planned.