2.2 Whole numbers: Int
Page 3 of 9
2.2.1 What an integer is
An integer is a whole number: positive, zero or negative, with no fraction. 7, 0 and -1205 are integers; 19.90 is not. Una's integer type is Int, and it has no largest value: an Int can be as large as the computer's memory allows.
Most numbers in a store are counts of whole things: units on a shelf, lines of an order, labels to print. Money is one too, once you count it in its smallest unit. A price of 19.90 is 1990 cents, and an Int holds 1990 exactly.
2.2.2 Why money is whole cents
A price written with a decimal point looks natural, so try it:
module shelf
--- Prints the price of a desk lamp, written with a decimal point.
pub main() -> Unit
uses @console: Console[print]
=
let lamp = 19.90
@console.print("{lamp}")[U0101] Error: `19.90` is a fractional literal; Una's integer literals are decimal
╭─[ src/shelf.una:7:17 ]
│
7 │ let lamp = 19.90
│ ─┬
│ ╰── `19.90` is a fractional literal; Una's integer literals are decimal
│
│ Note: run `una explain U0101` for an explanation
───╯The message says that 19.90 is a fractional literal, a number with a fraction, and that Una's integer literals are written in decimal digits only. Una has no type for numbers with a fraction today.
For money, whole cents work well. Many languages store a fraction such as 0.10 as a binary approximation, so that adding prices gives totals such as 0.30000000000000004, and every program rounds them in its own way, often without saying so. With whole cents, every sum and product is exact, and the one place a fraction appears, a division, says how it rounds. Money is an Int of cents in this chapter and in every chapter of this book.
2.2.3 Numbers with a fraction: not in this edition
Edition 0.2, which this book uses, has no type for numbers with a fraction. The preview editions add two kinds. A decimal type holds amounts such as 19.90 exactly, in base ten, as people write them (edition 0.5). Floating-point types hold approximate values over a very wide range, for measurements and science, where a tiny rounding error does not matter (F64 in edition 0.3, F32 in edition 0.5). A preview edition may still change (chapter 19), and this book does not use these types. In edition 0.2, keep money in cents and measures in whole small units, such as grams or millimeters, all as Int.
2.2.4 How to write integers and arithmetic
2.2.4.1 Integer literals
- Write an integer in decimal digits:
7,1990. - Group the digits with
_to make large numbers readable:1_990,10_000,1_000_000. An_goes only between two digits: never two in a row, never at the start or the end. - For a negative number, write a minus sign in front:
-1205. - A literal has no leading zero, except
0itself:007is not a literal. A number with a leading zero shows whatuna checksays.
2.2.4.2 The operators
An operator is a sign that computes a value from the values next to it, its operands, as + does in 7 + 2.
| Operator | Meaning | 7 and 2 give |
|---|---|---|
+ |
addition | 7 + 2 is 9 |
- |
subtraction, or a minus sign in front of one value | 7 - 2 is 5, -7 is minus seven |
* |
multiplication | 7 * 2 is 14 |
/ |
division, dropping the remainder | 7 / 2 is 3 |
mod |
the remainder of the division | 7 mod 2 is 1 |
2.2.4.3 The order of operations
*,/andmodcome before+and-, as in school arithmetic:2 + 3 * 4is 14.- Operators of the same level go from left to right:
20 - 6 - 4is 10. - A minus sign in front of one value comes first of all:
-7 / 2divides minus seven by 2. - Parentheses change the order:
(2 + 3) * 4is 20.
2.2.5 The operators at work
The step tries each operator on 7 units packed 2 to a box:
let units = 7
let per_box = 2
@console.print("{units + per_box}, {units - per_box} and {units * per_box}")
@console.print("{units / per_box} full boxes, {units mod per_box} unit left over")
@console.print("{-units} and {per_box - units}")
@console.print("{2 + 3 * 4} and {(2 + 3) * 4}")
@console.print("{20 - 6 - 4} and {20 - (6 - 4)}")
@console.print("{1_000_000 * 1_000_000}")9, 5 and 14
3 full boxes, 1 unit left over
-7 and -5
14 and 20
10 and 18
10000000000007 / 2 gives 3 full boxes and drops the half, and 7 mod 2 gives the 1 unit left over. 20 - (6 - 4) computes the parentheses first: 20 − 2 is 18. 1_000_000 * 1_000_000 is exact, with all its zeros.
2.2.6 Money as Int cents
A price never needs a fraction, so it never needs rounding until the code chooses one:
module prices
--- Prints a few computations on prices in cents.
pub main() -> Unit
uses @console: Console[print]
=
let lamp = 1_990
let rug = 4_500
let order = 2 * lamp + rug
@console.print("order: {order} cents, or {order / 100} units and {order mod 100} cents")
let discount = order * 15 / 100
@console.print("15% off: {discount} cents off, {order - discount} to pay")
let refund = -1_205
@console.print("refund: {refund / 100} and {refund mod 100}")
let past_64_bits = 9_223_372_036_854_775_807 + 1
@console.print("no overflow: {past_64_bits}")let order = 2 * lamp + rug. Multiplication first, then addition: 2 lamps at 1990 cents and a rug at 4500.order / 100andorder mod 100. Division of twoIntvalues gives a whole number and drops the remainder;modgives the remainder. Together they split cents into whole units of money and cents.order * 15 / 100. A percentage. Multiply first, then divide, so that nothing is dropped before the division.refund / 100andrefund mod 100. Division of a negative amount.9_223_372_036_854_775_807 + 1. The largest value that many languages can hold in a whole number, plus one.
una run . prints:
order: 8480 cents, or 84 units and 80 cents
15% off: 1272 cents off, 7208 to pay
refund: -13 and 95
no overflow: 9223372036854775808The discount is 15 percent of 8480 cents, 1272: the exact value is 1272.0, so nothing is dropped. Where a percentage does not come out whole, / drops the fraction, and so rounds down. The refund line is the subject of Euclidean division.
2.2.7 Functions on whole numbers: abs, min and max
Una gives every module a few functions on Int, ready to call, without writing them. They belong to the prelude, the set of functions every module has, which section 3.2 presents:
abs(x)is the distance ofxfrom zero:abs(-3)is 3, andabs(3)is 3.min(a, b: c)is the smaller of two values, andmax(a, b: c)the larger. The second argument carries its label,b, as every argument after the first does.
The step computes three facts about the stock of one SKU:
module stock
--- Prints what `abs`, `min` and `max` give for the stock of one SKU.
pub main() -> Unit
uses @console: Console[print]
=
let on_shelf = 14
let reserved = 17
let counted = 11
@console.print("free to sell: {max(on_shelf - reserved, b: 0)}")
@console.print("one customer may buy: {min(on_shelf, b: 10)}")
@console.print("the count is off by {abs(counted - on_shelf)}")max(on_shelf - reserved, b: 0). 14 − 17 is −3: more units are promised to orders than the shelf holds.maxwith 0 makes the answer 0, never below.min(on_shelf, b: 10). A limit of 10 units per customer, or fewer when the shelf holds fewer.abs(counted - on_shelf). How far a count is off, whichever way: 11 − 14 is −3, and its distance from zero is 3.
free to sell: 0
one customer may buy: 10
the count is off by 32.2.8 How Int behaves
2.2.8.1 No 64-bit limit
The last line of prices shows that Int has no 64-bit limit: the sum is exact. Many languages store whole numbers in 64 bits, binary digits, and a sum past the largest 64-bit value wraps around to a large negative number, or stops the program. In Una it is just a larger number.
2.2.8.2 Euclidean division
The refund line of prices shows how Una divides a negative number. Division and mod are Euclidean: the remainder is never negative, and the quotient is chosen to make that true. So -1205 / 100 is -13 and -1205 mod 100 is 95, since −13 × 100 + 95 is −1205. Many languages round toward zero instead, and give −12 and −5. For amounts that are not negative, both rules agree, so a function that splits cents into units and cents is right for every amount that is not negative.
2.2.8.3 Division by zero, a proof obligation
Dividing by zero has no answer, so Una does not let a program reach such a division. Here is a function whose divisor comes from a parameter:
module split
--- What each of `people` pays when they share a bill of `total` cents, rounded down.
pub share(total: Int, people: Int) -> Int = total / people
--- Prints one share of a bill.
pub main() -> Unit
uses @console: Console[print]
=
@console.print("{share(9000, people: 4)} cents each")[U5001] Error: division obligation `people != 0` is refuted
╭─[ src/split.una:4:45 ]
│
4 │ pub share(total: Int, people: Int) -> Int = total / people
│ ───────┬──────
│ ╰──────── division obligation `people != 0` is refuted
│
│ Help: repair 1: guard the division with `if people != 0`
│
│ Note 1: obligation ob-7797c5169054 (division) is refuted: people != 0
│
│ Note 2: counterexample: people = 0
│
│ Note 3: run `una explain U5001` for an explanation
───╯Read it in three steps, as in chapter 1:
- The message.
una checkturned the division into a proof obligation: a fact that must be proved before the program may run. Here it ispeople != 0, "people is not zero". The part ofuna checkthat proves such facts is the verifier. It asks Z3, the solver you installed in chapter 1, whether the fact holds for every value the parameters can take. It does not, so the obligation is refuted, and the code is U5001. - The place. The marks point at the whole division,
total / people. - The notes.
Note 2: counterexample: people = 0gives a value that breaks the obligation, a counterexample: a call such asshare(9000, people: 0)would divide by zero.Note 1repeats the obligation with its identifier,ob-…, which tools use to name it.
A divisor written as a literal other than zero, such as 100, needs no proof. For a divisor that comes from a parameter, the function must say why it cannot be zero. The Help line proposes a guard: an if that runs the division only when people != 0, "people is not equal to 0", holds (section 3.4 teaches if). The other way is a precondition, a rule every caller must meet, such as "people is greater than 0" (section 5.1).
2.2.8.4 Dividing by the literal 0
A division by the literal 0 can never be safe. Change one line of arithmetic, so that it divides by 0:
--- a/src/arithmetic.una
+++ b/src/arithmetic.una
@@ -15 +15 @@
- @console.print("{1990 * 3 / 100}")
+ @console.print("{units / 0}")[U5001] Error: division obligation `0 != 0` is refuted
╭─[ src/arithmetic.una:15:20 ]
│
15 │ @console.print("{units / 0}")
│ ────┬────
│ ╰────── division obligation `0 != 0` is refutedThe obligation is 0 != 0, false whatever the values are, so it needs no counterexample.
Note
An Int that may grow past the computer's own number size costs a little more to compute with than a number of a fixed size. Where a number must have a fixed size, such as a number another program reads as one byte, use the fixed-width types of section 2.3.
2.2.9 Int or something else
Which to use:
| The number is… | Use |
|---|---|
| A count, a quantity or an amount of money | Int, with money in cents |
| A field that another program, a file or a device reads with a fixed size | a fixed-width type (section 2.3) |
| A code made of digits, such as a postal code with a leading zero | Text: you never compute with it, and 01310 is not an integer literal |
| A price with a fraction | Int cents, written with two decimals where the program prints it, as exercise 3 does |
| A measure with a fraction | Int in a smaller unit, such as grams or millimeters |
2.2.10 Check yourself: integers
The step arithmetic ends with two more lines:
@console.print("{1990 * 3 / 100}")
@console.print("{-7 / 2} and {-7 mod 2}")What do they print? The first is three units at 19.90, in whole units of money.
Show the answer
59
-4 and 11990 * 3 is 5970, and / 100 drops the remainder: 59. In -7 / 2, the minus sign comes first, and Euclidean division keeps the remainder at 0 or above: −4 × 2 is −8, and −7 − (−8) is 1. So the quotient is −4 and the remainder 1.