cromo La guida di Cromo
Scarica PDF EN

Il nucleo

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.

Generata dalla documentazione nei sorgenti della libreria, che è in inglese.

#Funzioni predefinite

#print

cromo
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 with string text() const as 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, as Point { x: 1, y: 2 } or a string between quotes
  • {{ and }} the braces themselves

#println

cromo
void println(string format, ...)

Writes format on the standard output as print does, and then a newline.

cromo
println("Hello {}, you are {} years old", name, age)
println("average: {:.2f}", average)

#eprint

cromo
void eprint(string format, ...)

Writes format on the standard error as print does, without a newline.

#eprintln

cromo
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

cromo
string format(string format, ...)

The text that print would write, with the same placeholders, in a new string.

cromo
string s = format("{} + {} = {}", 2, 3, 5)   // "2 + 3 = 5"

#panic

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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

cromo
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")).

cromo
list<u8> logo = embed("images/logo.png")

#Tipi predefiniti

#bool

cromo
bool

A truth value, true or false, in a byte.

#char

cromo
char

A 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

cromo
i8

An 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

cromo
i16

An 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

cromo
i32

An 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

cromo
i64

An 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

cromo
u8

An 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

cromo
u16

An 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

cromo
u32

An 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

cromo
u64

An 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

cromo
f32

A floating-point number of 32 bits, float of C, with about 7 digits.

#f64

cromo
f64

A floating-point number of 64 bits, double of C, with about 16 digits.

#Tipi

#list

cromo
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.

cromo
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

cromo
i64 len() const

The number of elements.

#list.add

cromo
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

cromo
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

cromo
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

cromo
void clear()

Removes all the elements, which are destroyed. The list keeps its memory for the elements that come next.

#list.reserve

cromo
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

cromo
list<T> slice(i64 from, i64 to) const

A 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

cromo
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

cromo
i64 indexOf(T value) const

The 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

cromo
bool contains(T value) const

Whether an element of the list is equal to value, compared with == as in indexOf.

#list.copy

cromo
list<T> copy() const

A new list with a copy of each element, the same that b = a makes.

#list.map

cromo
list<U> map<U>(func(T) U f) const

A 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.

cromo
list<string> labels = numbers.map<string>([](i64 n) string { ret format("#{}", n) })

#list.filter

cromo
list<T> filter(func(T) bool keep) const

A new list with a copy of the elements for which keep is true, in their order.

cromo
list<i64> even = numbers.filter([](i64 n) bool { ret n % 2 == 0 })

#string

cromo
struct string : Key, Ordered

Text 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.

cromo
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

cromo
i64 len() const

The length in bytes, not in characters: "città".len() is 6.

#string.reserve

cromo
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

cromo
void append(string other)

Adds a copy of other at the end of the text, as +=.

#string.format

cromo
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

cromo
string concat(string other) const

A new text with other after this one, as +.

#string.equals

cromo
bool equals(string other) const

Whether the two texts have the same bytes, as ==.

#string.hash

cromo
u64 hash() const

A hash of the bytes, for the keys of a map.

#string.compare

cromo
i32 compare(string other) const

The 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

cromo
list<u8> bytes() const

A copy of the bytes of the text. string(bytes) makes a text of them again, after checking that they are UTF-8.

#string.slice

cromo
string slice(i64 from, i64 to) const

A 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

cromo
i64 find(string part) const

The position in bytes of the first part, or -1 if there is none. An empty part is found at 0.

#string.findFrom

cromo
i64 findFrom(string part, i64 from) const

The 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

cromo
i64 findLast(string part) const

The position in bytes of the last part, or -1 if there is none. An empty part is found at len().

#string.contains

cromo
bool contains(string part) const

Whether part is in the text; an empty part always is.

#string.startsWith

cromo
bool startsWith(string prefix) const

Whether the text begins with prefix; true for an empty prefix.

#string.endsWith

cromo
bool endsWith(string suffix) const

Whether the text ends with suffix; true for an empty suffix.

#string.split

cromo
list<string> split(string separator) const

The 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.

cromo
list<string> parts = "a,b,,c".split(",")   // "a", "b", "", "c"

#string.trim

cromo
string trim() const

A 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

cromo
string trimStart() const

A copy of the text without the spaces at its beginning, the same that trim removes.

#string.trimEnd

cromo
string trimEnd() const

A copy of the text without the spaces at its end, the same that trim removes.

#string.replace

cromo
string replace(string old, string new) const

A 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

cromo
string upper() const

A 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

cromo
string lower() const

A 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

cromo
string repeat(i64 count) const

The 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

cromo
string copy() const

A copy of the text, the same that b = a makes.

#Debug

cromo
interface Debug

The 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

cromo
interface Key

What 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.

cromo
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

cromo
u64 hash() const

A hash of the value: two values that are equal must give the same one.

#Key.equals

cromo
bool equals(Self other) const

Whether the value is equal to other.

#Ordered

cromo
interface Ordered

The 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

cromo
i32 compare(Self other) const

Negative when this value comes before other, zero when they are equal, positive when it comes after.

#map

cromo
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.

cromo
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

cromo
i64 len() const

The number of keys.

#map.contains

cromo
bool contains(K key) const

Whether the map has the key.

#map.remove

cromo
bool remove(K key)

Removes the key with its value, which are destroyed; false if the key was not there.

#map.copy

cromo
map<K, V> copy() const

A new map with a copy of each key and value, the same that b = a makes.

#Exception

cromo
interface Exception

What 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.

cromo
struct NotFound : Exception {
    string name

    string message() const {
        ret format("{} was not found", name)
    }
}

The guide: Errors.

#Exception.message

cromo
string message() const

The text of the error, for who reads it.

#Error

cromo
struct Error : Exception

A ready-made exception with its message, for the errors that need no type of their own: throw Error(format("invalid age {}", age)).

cromo
Error(move string description)

An exception whose message is description.

#Option

cromo
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.

cromo
Option<i64> found = indexOf(names, "anna")
switch (found) {
    case Some(i64 at) {
        println("at {}", at)
    }
    case None {
        println("missing")
    }
}
  • None
  • Some(T value)

#Option.has

cromo
bool has() const

Whether there is a value.

#Option.value

cromo
T value() const

The value; a panic when there is none: has() tells, or or(other) gives another one.

#Option.or

cromo
T or(T other) const

The value, or other when there is none.

#Funzioni

#join

cromo
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

cromo
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

cromo
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.

cromo
list<string> words = ["pear", "fig", "banana"]
sort(ref words)   // "banana", "fig", "pear"

#sortBy

cromo
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.

cromo
sortBy(ref words, [](string a, string b) bool { ret a.len() < b.len() })