Getting startedSlide 9 of 86
9UInt8Getting started
Sized numbers
When a program keeps many small numbers, each can take only the bits it needs:
UInt1…UInt64are unsigned integers of that many bits, so aUInt4holds 0 to 15.Int1…Int63are signed, so anInt4holds −8 to 7.Int64is another name forInt.Float32is a 32-bit float, about seven digits.Float64is another name forFloat.- A sized integer wraps at its own width, the way
Intwraps at 64: aUInt4at 15 plus one is 0.-on an unsigned type is a compile error. - A literal takes the type it lands in, and has to fit it:
UInt4 x = 16is a compile error. - No number changes type on its own: a
UInt8becomes anIntonly throughInt(x), aFloat32aFloatonly throughFloat(x), andUInt4 + UInt8is a compile error until one side is converted. Two integers of any sizes still compare by value. UInt4(x)keeps the low bits and never fails, andUInt4.checked(x)answersError(x)wherexdoes not fit.- A sized index is its own bounds proof: a
UInt4indexes any vector of 16 or more with no guard. - A vector of them is packed, each value taking only its own bits: a million
UInt4s take half a megabyte.
type Pixel {
r: UInt8
g: UInt8
b: UInt8
}
proc main(): void {
UInt4 level = 15
echo level + 1 // 0 — a UInt4 wraps at 16
Int wide = Int(level) // widened, and said so
echo wide + 1 // 16
echo UInt8(300) // 44 — the low 8 bits
echo UInt8.checked(300) // Error(300)
echo Pixel(255, 128, 0) // {255, 128, 0}
Float32 third = 0.1
echo third // 0.1
Str[16] names = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
echo names[level] // p — no guard: a UInt4 is at most 15
UInt4[dyn] steps = [3, 1, 4, 1, 5, 9, 2, 6]
echo bytes(steps) // 8 — packed: all eight in one 64-bit word
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
Output
Run a program to see what it prints here.