Values and types

// ints are 64-bit and floats are IEEE 754 doubles
count = 3
price = 2.5
print(count * 2, price * 2.0)

// int division truncates toward zero, and % is its remainder
print(7 / 2, -7 / 2, 7.0 / 2.0)
print(7 % 2, -7 % 2, 7.5 % 2.0)

// ** raises to an int power
print(2 ** 10, 2.5 ** 2, 2.0 ** -1, -2 ** 2)

// ints and floats never mix, so convert one side
total = price * float(count)
print(total, int(total).unwrap())

// bools, strings, and options, which hold a value or none
ready = count > 2
name = "stone"
print(ready, not ready, name + "!", name.len())
print(some(name), none)

// a string writes the value of each {expression} in it, and str gives what print writes
print("{name} has {name.len()} letters, and {count} * 2 is {count * 2}")
print(str([1, 2]) + "!", "{{braces}}")

// floats print the way Python shows them
print(0.1 + 0.2, 1e16, 1.0 / 3.0)

prints

6 5.0
3 -3 3.5
1 -1 1.5
1024 6.25 0.5 -4
7.5 7
true false stone! 5
some('stone') none
stone has 5 letters, and 3 * 2 is 6
[1, 2]! {braces}
0.30000000000000004 1e+16 0.3333333333333333

The types

type

examples

notes

int

0, 42, -7, 0xff, 1_000

64-bit signed; overflow wraps, but dividing MIN by -1 and shifting bits off the top with << are errors

float

2.5, 1e16, 0.1

IEEE 754 double

bool

true, false

str

"hello", "a\tb\n"

double quotes only, cannot span lines; \n, \", and other escapes

bytes

b"GET\r\n", b"\x00\xff"

data that is not text, whose elements are ints from 0 to 255; see Bytes

list[T]

[1, 2, 3]

see Lists

tuple[A, B]

(1, "one")

a few values of different types; see Lists

map[K, V]

{"a": 1}, {}

values found by key; see Maps

option[T]

some(1), none

a value that may be missing; see Enums and options

result[T, E]

ok(1), err("no")

a value or an error; see Errors

Variables never have types written down. The checker infers each variable’s type from what is assigned to it, and a variable keeps that type: assigning "a" to a variable that holds an int is an error. The only types you write are in function signatures, as Functions shows.

Arithmetic

+, -, *, /, and % work on two ints or two floats, and + also joins two strings. stone never converts between int and float on its own, so price * count with a float price and an int count is an error. Convert explicitly with float(count), or int(price), which drops the fraction and gives a result, since a float may be nan or too large for an int: int(-2.5) is ok(-2), and int(-2.5).unwrap() is -2.

Division of ints truncates toward zero, as in C, so -7 / 2 is -3 rather than Python’s -4. % is the remainder of that division, so it takes the sign of the left side: -7 % 2 is -1 rather than Python’s 1, and a == a / b * b + a % b always holds. Dividing by zero with / or %, whether by 0 or 0.0, stops the program with division by zero.

** raises a number to a power: 2 ** 10 is 1024 and 2.5 ** 2 is 6.25. The exponent is always an int, even for a float base, so 2.0 ** -1 is 0.5 but 2.0 ** 0.5 is an error. An int raised to a negative exponent has no int result, so 2 ** -1 stops the program with negative exponent. As in Python, ** groups right to left and binds tighter than a minus sign before it, so 2 ** 3 ** 2 is 512 and -2 ** 2 is -4.

Each operator also updates a variable in place: count += 1 is count = count + 1, and -=, *=, /=, %=, and **= work the same way, on list elements too, as in scores[i] *= 2. See augmented assignment.

Bits

Ints also work as 64 bits of two’s complement, with Python’s bitwise operators: & keeps the bits set in both sides, | those set in either, ^ those set in exactly one, ~x flips every bit (so it is -x - 1), and x << n and x >> n move the bits n places, which is multiplying or dividing by 2 ** n, rounding down. Ints can be written in hexadecimal, octal, or binary, and any number may have _ between its digits to make it easier to read:

// flags packed into one int, one bit each
READ = 0b001
WRITE = 0b010
RUN = 0b100

fn describe(mode: int) -> str:
    text = ""
    for flag, letter in [(READ, "r"), (WRITE, "w"), (RUN, "x")]:
        if mode & flag != 0:
            text += letter
        else:
            text += "-"
    ret text

mode = READ | WRITE
print(describe(mode), describe(mode ^ RUN), describe(mode & ~WRITE))

// the bytes of a 32-bit number, lowest first
n = 0xcafe_f00d
print([0, 8, 16, 24].map(|shift| (n >> shift) & 0xff))
print("{n:#x} {n:#b}")
print(1 << 10, -20 >> 2, 6 & 3, 6 | 3, 6 ^ 3, ~6)

prints

rw- rwx r--
[13, 240, 254, 202]
0xcafef00d 0b11001010111111101111000000001101
1024 -5 2 7 5 -7

These operators bind looser than arithmetic and tighter than comparisons, so mode & flag != 0 means (mode & flag) != 0. On two bools, &, |, and ^ give a bool, evaluating both sides where and and or may stop after the first. A shift count must be from 0 to 63, and a << whose result does not fit in an int stops the program with integer overflow in shift, so 1 << 62 is fine but 1 << 63 is not, where + and * would wrap around. They also update a variable in place, as flags |= WRITE does.

Strings

Strings index and slice like lists, compare in dictionary order with < and >, can be walked one character at a time with for, and have methods such as split, splitlines, join, find, rfind, count, replace, lower, upper, startswith, and endswith. find gives an option, none if the text never appears, which unwrap opens when it must be there:

line = "name=stone"
at = line.find("=").unwrap()
print(line[:at], line[at + 1:], line[0], line[-1])   // name stone n e
print("apple" < "banana", line.startswith("name"))   // true true
print("-".join(line.split("=")))                     // name-stone

Any expression in braces inside a string is written into it, so "{name} has {xs.len()} items" builds a string from values of any type, with no prefix needed, and {{ and }} write braces. Indexes count bytes, so a character outside ASCII, such as é, takes more than one. See Types for the details.

Printing

print takes any number of values, prints them separated by spaces, and ends the line. Floats print the way Python’s repr shows them: the shortest digits that read back as the same float, which is why 0.1 + 0.2 prints as 0.30000000000000004. str(x) gives the text print would write for any value, and a value in a string is written the same way.

Next, Control flow.