2 Numbers
Page 1 of 9
A store counts all day: units on a shelf, lines of an order, boxes for a parcel, prices in cents. In chapter 1 every value your programs used was a text. This chapter adds numbers. You learn what a value and its type are, how to give a value a name with let, and how to print a number. Then you meet Una's whole numbers, Int, which never overflow, and the fixed-width integers, such as U8, for the places where a number must fit a set size. You end with the packing slip that goes into the box of an order, checked, run and tested.
What you'll build
A packing slip: the sheet that goes into the box with an order, so that the customer can check what arrived. The program prints the slip of one sample order:
Packing slip for order 1042
Ship to customer 318 <customer318@example.invalid>
2 x LAMP-01 Desk lamp, brass
1 x RUG-07 Wool rug, 120 by 180 cm
3 units in 2 lines
Boxes in this shipment: 2
Total paid: 8480 cents
Questions? Write to orders@example.invalid and quote the order number.You will learn to:
- give values names with
let, and say what type a name holds; - put numbers into a text, so that
printcan show them; - compute with whole numbers:
+,-,*,/andmod, in the right order; - keep money exact, as whole cents;
- choose a fixed-width type, such as
U32, when a number must fit a set size.
Download this chapter's packages: each step is a package under steps/, and the chapter's program is day-to-day/; run una check . and una run . in one.
Why it works this way
In many languages the plain numbers are where quiet mistakes live. A whole number has a largest value, and a total that grows past it jumps to a wrong number, often a negative one, with no error. A price such as 0.10 is stored as an approximation, so that adding prices can give 0.30000000000000004. A division by zero stops the program while it runs, in front of a customer. A number can be turned into a text, or a text into a number, without a word in the code, and the result is not what anyone meant.
Una makes each of these a rule that una check enforces before the program runs:
Inthas no largest value. A sum or a product of whole numbers is always exact, however large it grows.- There are no inexact numbers. Una has no type for fractions yet, so an amount such as 19.90 is counted in whole cents, the
Int1990, and nothing rounds unless the code says how. - A division must be safe. A division by a value that may be zero does not pass the check, and the check says which value breaks it.
- A fixed size is proved. Where you choose a type with a set size, every operation on it must be proved to stay inside that size.
- No value changes its type on its own. A number becomes a text only where the code puts it into one.
A number in Una means exactly what its type says: an
Intis exact at any size, and a fixed-width value never leaves its range while the program runs.