The core
The core of the standard library: string, list and map, the interfaces Ordered, Key and Debug, the functions that sort, and Exception and Error. Every module sees its names without importing them; a name that a module declares comes first, so a name added here never breaks a program. The built-in functions, as println, and the types of the numbers belong to the language.
The guide: Lists, maps and text.
Made from the documentation in the sources of the library.
#Built-in functions
void print(string format, ...)Writes format on the standard output, with the arguments in place of its placeholders, and no newline. The format is a string literal, which the compiler checks against the arguments, as std::format of C++:
{}a value as it is; a struct or an enum withstring text() constas its text{0}the argument at that position, from 0{:>8},{:<8},{:^8}the value in 8 characters, on the right, on the left or at the center{:.2f}a number with 2 decimals;{:x},{:b},{:o}an integer in hexadecimal, binary or octal{:?}the form for debugging of any value, asPoint { x: 1, y: 2 }or a string between quotes{{and}}the braces themselves
#println
void println(string format, ...)Writes format on the standard output as print does, and then a newline.
println("Hello {}, you are {} years old", name, age)
println("average: {:.2f}", average)#eprint
void eprint(string format, ...)Writes format on the standard error as print does, without a newline.
#eprintln
void eprintln(string format, ...)Writes format on the standard error as println does, with a newline: for errors and messages that must not mix with the output of the program.
#format
string format(string format, ...)The text that print would write, with the same placeholders, in a new string.
string s = format("{} + {} = {}", 2, 3, 5) // "2 + 3 = 5"#panic
void panic(string reason)Stops the program on purpose, as an index out of range does: it writes panic: with the reason, the place and the calls that led there on the standard error, and ends with the exit code 101. It is for the errors of the program, and cannot be caught; for an error that the caller can handle, throw an exception.
#assert
void assert(bool condition)Stops the program with a panic when condition is false. The panic writes the condition as it is written and, for a comparison of numbers, the values of its sides: assertion failed: total == 7 (total is 6). It works also with --release, and the tests use it to check their results.
#wrapAdd
T wrapAdd(T a, T b)The sum of two integers of the same type, keeping the low bits when it goes out of the range, without the check of overflow, also in debug: for hashes, checksums and random numbers.
#wrapSub
T wrapSub(T a, T b)The difference of two integers of the same type, keeping the low bits when it goes out of the range, without the check of overflow, also in debug.
#wrapMul
T wrapMul(T a, T b)The product of two integers of the same type, keeping the low bits when it goes out of the range, without the check of overflow, also in debug: for hashes, checksums and random numbers.
#countOnes
i32 countOnes(T x)The bits at 1 of an integer, of any type: countOnes(u8(0b1011)) is 3. It is one instruction of the processor, for the boards of bits and the sets of bits.
#trailingZeros
i32 trailingZeros(T x)The bits at 0 under the lowest bit at 1 of an integer: the index of that bit, from 0. trailingZeros(u32(8)) is 3, and for 0 it is the bits of the type, 64 for an i64.
#leadingZeros
i32 leadingZeros(T x)The bits at 0 over the highest bit at 1 of an integer: leadingZeros(u32(1)) is 31, and for 0 it is the bits of the type.
#rotateLeft
T rotateLeft(T x, n)The bits of an integer turned to the left by n: those that go out on the left come in on the right. n is an integer of any type, taken modulo the bits of the type, so a negative n turns to the right.
#rotateRight
T rotateRight(T x, n)The bits of an integer turned to the right by n: those that go out on the right come in on the left. n is an integer of any type, taken modulo the bits of the type.
#fma
T fma(T a, T b, T c)a * b + c with one rounding at the end, where the product and the sum by themselves round twice: for three f64 or three f32, or three vectors of them as f32x8. It is one instruction of the processor with --cpu x86-64-v3 and on ARM64, and a slower function with the same result elsewhere.
#embed
list<u8> embed(string path)The bytes of a file that the compiler reads and puts in the program: images and data that the program carries with it, also in the APK of Android. path is a string literal, from the folder of the source file that writes it; a file that is not there is an error of the compiler, and a file changed needs the program compiled again. Each call gives a copy of its own, which the program can change. For a text: string(embed("help.txt")).
list<u8> logo = embed("images/logo.png")#Built-in types
#bool
boolA truth value, true or false, in a byte.
#char
charA byte, the same type as u8, for the characters of ASCII. Its literals are written between single quotes, as in C, with the same escapes for a newline, a tab or a byte in hexadecimal.
#i8
i8An integer with sign of 8 bits, from -128 to 127. Out of the range, an operation stops the program in debug, and wraps around with --release.
#i16
i16An integer with sign of 16 bits, from -32768 to 32767. Out of the range, an operation stops the program in debug, and wraps around with --release.
#i32
i32An integer with sign of 32 bits, from -2147483648 to 2147483647, int of C. Out of the range, an operation stops the program in debug, and wraps around with --release.
#i64
i64An integer with sign of 64 bits, from -9223372036854775808 to 9223372036854775807: the lengths and the indices of lists and strings. Out of the range, an operation stops the program in debug, and wraps around with --release.
#u8
u8An integer without sign of 8 bits, from 0 to 255: a byte. Out of the range, an operation stops the program in debug, and wraps around with --release.
#u16
u16An integer without sign of 16 bits, from 0 to 65535. Out of the range, an operation stops the program in debug, and wraps around with --release.
#u32
u32An integer without sign of 32 bits, from 0 to 4294967295. Out of the range, an operation stops the program in debug, and wraps around with --release.
#u64
u64An integer without sign of 64 bits, from 0 to 18446744073709551615. Out of the range, an operation stops the program in debug, and wraps around with --release.
#f32
f32A floating-point number of 32 bits, float of C, with about 7 digits.
#f64
f64A floating-point number of 64 bits, double of C, with about 16 digits.
#Types
#list
struct list<T>A list of values of type T that grows as needed, as std::vector in C++: the elements are one after the other on the heap, and the list destroys them when it ends. [a, b, c] makes a list, and v[i] is the element itself, which can be read, assigned, passed with ref and moved; an index out of the list is a panic. for (T x in v) visits the elements, and for (ref T x in v) can change them; while it runs, the list cannot change its length. A list is copied where it is given without move, as b = a.
list<i64> numbers = [5, 3, 8]
numbers.add(13)
numbers.insert(0, 1) // 1, 5, 3, 8, 13
i64 removed = numbers.remove(2) // 3
for (ref i64 n in numbers) {
n *= 2
}The guide: Lists, maps and text.
#list.len
i64 len() constThe number of elements.
#list.add
void add(move T value)Adds the value at the end of the list. A value that owns resources, as a string, is copied, unless it is given with move: names.add(move name).
#list.insert
void insert(i64 index, move T value)Puts the value at index, and the elements from there on move one place forward. index goes from 0 to len(), which adds at the end; outside, it is a panic. The value is copied or moved as in add.
#list.remove
T remove(i64 index)Removes the element at index and gives it back; the elements after it move one place back. An index out of the list is a panic.
#list.clear
void clear()Removes all the elements, which are destroyed. The list keeps its memory for the elements that come next.
#list.reserve
void reserve(i64 count)Makes room for count elements in all, so that adding them up to that number does not move the elements again.
#list.slice
list<T> slice(i64 from, i64 to) constA new list with a copy of the elements from from to to excluded, as slice of a string: [10, 20, 30, 40].slice(1, 3) is [20, 30]. A position out of the list, or from after to, is a panic.
#list.append
void append(list<T> other)Adds a copy of each element of other at the end of the list, in their order: all.append(more). The other list does not change.
#list.indexOf
i64 indexOf(T value) constThe place of the first element equal to value, from 0, or -1 when there is none. The elements are compared with ==: the list must be of values that have it, as numbers, strings, and the structs and the enums whose fields have it.
#list.contains
bool contains(T value) constWhether an element of the list is equal to value, compared with == as in indexOf.
#list.copy
list<T> copy() constA new list with a copy of each element, the same that b = a makes.
#list.map
list<U> map<U>(func(T) U f) constA new list with what f gives for each element, in their order. The list does not change; an exception of f goes on to the caller.
list<string> labels = numbers.map<string>([](i64 n) string { ret format("#{}", n) })#list.filter
list<T> filter(func(T) bool keep) constA new list with a copy of the elements for which keep is true, in their order.
list<i64> even = numbers.filter([](i64 n) bool { ret n % 2 == 0 })#string
struct string : Key, OrderedText in UTF-8, which owns its bytes, as std::string in C++. The length and the positions are in bytes: s[i] is a u8, and a letter outside ASCII takes more than one byte. Two strings are compared with == and <, byte by byte, and joined with + and +=. A string is copied where it is given without move, as b = a; a literal takes no memory of its own until it changes.
string clean = " Hello, World ".trim() // "Hello, World"
i64 at = clean.find("World") // 7
string word = clean.slice(0, 5).upper() // "HELLO"
list<string> parts = "a,b,,c".split(",") // "a", "b", "", "c"The guide: Lists, maps and text.
#string.len
i64 len() constThe length in bytes, not in characters: "città".len() is 6.
#string.reserve
void reserve(i64 count)Makes room for count bytes in all, so that appending up to that length does not allocate memory again.
#string.append
void append(string other)Adds a copy of other at the end of the text, as +=.
#string.format
void format(string text)Replaces the text with the one that a format and its arguments give, as format does: s.format("{} of {}", done, total).
#string.concat
string concat(string other) constA new text with other after this one, as +.
#string.equals
bool equals(string other) constWhether the two texts have the same bytes, as ==.
#string.hash
u64 hash() constA hash of the bytes, for the keys of a map.
#string.compare
i32 compare(string other) constThe order of the two texts, byte by byte, which in UTF-8 is the order of the code points: -1 when this one comes first, 0 when they are equal, 1 when it comes after. A text comes after its beginning: "ab" after "a".
#string.bytes
list<u8> bytes() constA copy of the bytes of the text. string(bytes) makes a text of them again, after checking that they are UTF-8.
#string.slice
string slice(i64 from, i64 to) constA copy of the bytes from from to to excluded: "città".slice(0, 3) is "cit". A position out of the text, from after to, or a slice that cuts a character of UTF-8 in two, is a panic.
#string.find
i64 find(string part) constThe position in bytes of the first part, or -1 if there is none. An empty part is found at 0.
#string.findFrom
i64 findFrom(string part, i64 from) constThe position in bytes of the first part at from or after it, or -1 if there is none. from goes from 0 to len(); outside, it is a panic.
#string.findLast
i64 findLast(string part) constThe position in bytes of the last part, or -1 if there is none. An empty part is found at len().
#string.contains
bool contains(string part) constWhether part is in the text; an empty part always is.
#string.startsWith
bool startsWith(string prefix) constWhether the text begins with prefix; true for an empty prefix.
#string.endsWith
bool endsWith(string suffix) constWhether the text ends with suffix; true for an empty suffix.
#string.split
list<string> split(string separator) constThe parts of the text between the separators, which are not in the parts. Two separators side by side give an empty part, and a text without the separator gives one part, all of it, also when it is empty. An empty separator is a panic.
list<string> parts = "a,b,,c".split(",") // "a", "b", "", "c"#string.trim
string trim() constA copy of the text without the spaces at its two ends: the space, the tab, the line feed, the carriage return, the vertical tab and the form feed of ASCII.
#string.trimStart
string trimStart() constA copy of the text without the spaces at its beginning, the same that trim removes.
#string.trimEnd
string trimEnd() constA copy of the text without the spaces at its end, the same that trim removes.
#string.replace
string replace(string old, string new) constA copy of the text where every old becomes new, from the left and without overlaps: "aaa".replace("aa", "b") is "ba". An empty old is a panic.
#string.upper
string upper() constA copy of the text where the letters a-z become A-Z. The rest stays as it is, also the letters outside ASCII, as à.
#string.lower
string lower() constA copy of the text where the letters A-Z become a-z. The rest stays as it is, also the letters outside ASCII, as À.
#string.repeat
string repeat(i64 count) constThe text count times, one after the other: "ab".repeat(3) is "ababab". A count of 0 gives an empty text, a negative one is a panic.
#string.copy
string copy() constA copy of the text, the same that b = a makes.
#Debug
interface DebugThe types that have a form of debug, the text that {:?} prints: every type has it by itself, without declaring anything, but the functions and the interfaces. A generic that prints its T with {:?} asks for it: T : Debug.
#Key
interface KeyWhat the keys of a map implement. The numbers, bool and string have it by themselves; a struct implements it with hash and equals, where two values that are equal have the same hash.
struct Cell : Key {
i32 row
i32 column
u64 hash() const {
ret row.hash() ^ column.hash() << 1
}
bool equals(Cell other) const {
ret row == other.row && column == other.column
}
}#Key.hash
u64 hash() constA hash of the value: two values that are equal must give the same one.
#Key.equals
bool equals(Self other) constWhether the value is equal to other.
#Ordered
interface OrderedThe values that have an order, as sort needs. The numbers and string have it by themselves, and a struct implements it with compare. For two floats, compare gives 0 when one of them is a NaN.
#Ordered.compare
i32 compare(Self other) constNegative when this value comes before other, zero when they are equal, positive when it comes after.
#map
struct map<K : Key, V>A hash table that associates keys with values, as std::unordered_map in C++. The keys can be numbers, bool, string, or structs that implement Key; a key added to the map is a copy. m[k] = v, m[k] += v and m[k]++ add a missing key, with the default value, before changing it; reading a missing key in any other way is a panic, so ask first with contains. for (K key, V value in m) visits the map in no particular order, and with ref V value it can change the values. A map is copied where it is given without move.
map<string, i32> stock
stock["apples"] = 10
stock["apples"] += 2 // 12
stock["plums"]++ // 1: a missing key starts from 0
for (string fruit, i32 count in stock) {
println("{} {}", fruit, count)
}The guide: Lists, maps and text.
#map.len
i64 len() constThe number of keys.
#map.contains
bool contains(K key) constWhether the map has the key.
#map.remove
bool remove(K key)Removes the key with its value, which are destroyed; false if the key was not there.
#map.copy
map<K, V> copy() constA new map with a copy of each key and value, the same that b = a makes.
#Exception
interface ExceptionWhat can be thrown with throw: a type that implements it gives the text of the error with message(). catch (Exception e) catches any exception. Error is a ready-made one; a type of its own lets the caller catch it apart and read its fields.
struct NotFound : Exception {
string name
string message() const {
ret format("{} was not found", name)
}
}The guide: Errors.
#Exception.message
string message() constThe text of the error, for who reads it.
#Error
struct Error : ExceptionA ready-made exception with its message, for the errors that need no type of their own: throw Error(format("invalid age {}", age)).
Error(move string description)An exception whose message is description.
#Option
enum Option<T>A value, or none: what a function returns when it may have no result, as a search that finds nothing. Its default value is None.
Option<i64> found = indexOf(names, "anna")
switch (found) {
case Some(i64 at) {
println("at {}", at)
}
case None {
println("missing")
}
}NoneSome(T value)
#Option.has
bool has() constWhether there is a value.
#Option.value
T value() constThe value; a panic when there is none: has() tells, or or(other) gives another one.
#Option.or
T or(T other) constThe value, or other when there is none.
#Functions
#join
string join(list<string> parts, string separator)The parts one after the other, with separator between them: join(["a", "b", "c"], ", ") is "a, b, c". An empty list gives an empty text.
#debugText
string debugText<T : Debug>(T value)The form of debug of a value, the text that {:?} prints: [1, 2] for a list, Point { x: 1, y: 2 } for a struct, a string between quotes with its escapes.
#sort
void sort<T : Ordered>(ref list<T> items)Sorts the list from the smallest element, in the order of compare. The sort is stable: elements that are equal keep their order.
list<string> words = ["pear", "fig", "banana"]
sort(ref words) // "banana", "fig", "pear"#sortBy
void sortBy<T>(ref list<T> items, func(T, T) bool less)Sorts the list with less, which says whether its first value comes before the second. The sort is stable: elements that are equal keep their order. When less throws, the exception goes on to the caller, and the list keeps all its elements, perhaps in another order.
sortBy(ref words, [](string a, string b) bool { ret a.len() < b.len() })