Skip to content
Early preview. Maxon is under active development — incomplete in places, with breaking changes expected before a 1.0 release.

Collections

Array is a growable, contiguous, generic sequence. Declare a concrete type with typealias, or write a literal: [1, 2, 3]. Array implements Iterable and Cloneable; it is also Hashable and Equatable when its element is. equals (and ==) compares two arrays element by element through the element’s own equals, and equal arrays hash equal. hash() is a Hasher fold, so it differs between processes. An array whose elements are equal exactly when their bits are (every integer type, Byte included, and a payload-free enum that declares neither hash nor equals) is folded as one run of its storage bytes; any other array (float, String, an element with its own hash or equals) folds each element’s hash() in turn.

typealias Score = int(i64.min to i64.max)
typealias ScoreArray = Array with Score
function main() returns ExitCode
let a = ScoreArray.create(0)
a.push(5)
a.push(1)
a.push(4)
let last = try a.pop() otherwise 0
a.insert(0, value: 9)
a.sort()
for x in a 'each'
print("{x} ")
end 'each'
a.sortBy(function(x Score, y Score) gives y.compare(x))
let first = try a.first() otherwise 0
let missing = try a.get(50) otherwise -1
print("\n{last} {first} {missing} {a.contains(9)}\n")
return 0
end 'main'

Output: 1 5 9 and 4 9 -1 true.

Member Returns Description
Array.create(0) Array An empty array. A call with no argument is refused at compile time (E3195): every array states its capacity.
Array.create(n) Array n zero-valued elements, in one allocation when they take at most 256 bytes. n is an ElementIndex. Refused at compile time (E3106) for an element type with no zero value — a struct, a String, a nested container, a Promise, a ranged alias that excludes 0, or an enum or union whose raw values include no 0; create those with create(n, zeroed: false). create(n, zeroed: true) follows the same rule.
Array.create(n, zeroed: false) Array An empty array with room for n elements, in one allocation when they take at most 256 bytes; append with push. n is an ElementIndex and zeroed: is a literal true or false. Available for every element type.
[a, b, c] Array A literal; its element type is inferred from context or from the first element.
clone() Array An independent copy. Each record, String or union element is cloned; an array of scalars shares its storage copy-on-write, which separates on the first write to either, unless the storage was created at a known size of at most 256 bytes, which is copied at once. An element that is a record holding a field at an interface type is copied through that field’s conformer; an element held at an interface type itself is refused (an element slot is one machine word). A copy of an element that is or holds a promise is E3141, here and at slice and append.
Array.from(source Iterable) Array Collect every element of an iterable, called through an alias (ScoreArray.from(range)). The iterable must bind Element to the alias’s own element (E3127).
Array.init(managed) Array Wrap raw compiler-managed storage; used by the compiler and the library.
managed field The array’s raw storage, for appendMemory and library code. Library tier: reading it elsewhere is E3185.
Member Returns Description
count() Count Number of elements.
isEmpty() bool True when count() is 0.
capacity() int(i64.min to i64.max) Slots allocated. Negative when the storage is not this array’s own yet: -1 for a slice view that has not been written, other negative values for a literal’s or a module-level constant’s read-only storage. Treat any negative value as “not owned yet”. A slice or clone copied from co-allocated storage owns its storage and reports the larger of its length and 4, or 0 when empty.
get(index) Element Throws ArrayError.indexOutOfBounds at or past count(), ArrayError.emptySlot for a slot that was never written.
first() Element Throws like get(0).
last() Element Throws indexOutOfBounds when empty.
slice(start, endIndex) Array Elements [start, endIndex). Throws indexOutOfBounds for a reversed or out-of-range pair; nothing is clamped.
contains(element Element) bool Element test. Requires Element is Equatable.
containsSequence(sequence Array) bool True when sequence occurs contiguously. An empty sequence is always contained. Requires Element is Equatable.
Member Description
set(index, value Element) Replace an element. Throws indexOutOfBounds at or past count(), even when capacity exists there.
push(value Element) Append one element.
append(other Array) Append every element of another array.
appendMemory(source) Append every element of raw storage (another array’s managed) without wrapping it in an Array. Its argument is library-tier storage, so library code calls it; a program appends another array with append.
pop() Remove and return the last element. Throws indexOutOfBounds when empty.
insert(at, value Element) Insert, shifting later elements right. An at past the end appends.
remove(at) Remove and return the element at at. Throws indexOutOfBounds.
clear() Remove every element, keeping the capacity.
Member Description
reserve(minCapacity) Ensure an existing array has at least minCapacity slots; a new array is sized by create(n, zeroed: false). A capacity no allocation can satisfy (u64.max) panics.
resize(newLength) Set the length. Growing exposes zero-valued elements, so it is refused at compile time (E3106) for an element type that is not a plain value — a struct, a String, a nested container, a Promise — and for a ranged alias that excludes 0 or an enum or union whose raw values include no 0, as create(n) is. Use growFilled or truncate for those.
truncate(newLength) Shorten to newLength, releasing the removed elements. A longer newLength does nothing.
growFilled(newLength, value Element) Lengthen to newLength, setting only the added elements to value. Grows capacity geometrically, so repeated small extensions stay amortized linear. A shorter newLength does nothing.
refill(newLength, value Element) Set the length to newLength and write value into every element, growing or shrinking.

An array grows by doubling while small and eases toward 1.25x once it is large.

Member Description
sort() Stable sort by Comparable.compare. Requires Element is Comparable.
sortUnstable() Unstable sort (pattern-defeating quicksort). Requires Element is Comparable.
sortBy(cmp function(Element, Element) returns Ordering) Stable sort by a comparator; any element type.
sortUnstableBy(cmp function(Element, Element) returns Ordering) Unstable sort by a comparator.
Member Returns Description
createIterator() ArrayIterator Positioned at the first element. Throws IterationError.exhausted when empty.
cursor() ArrayIterator The same as createIterator().

map, filter, containsWhere(predicate) and withIterator come from Iterable.

enum ArrayError implements Error
indexOutOfBounds
emptySlot
end 'ArrayError'

indexOutOfBounds: the index was outside [0, count()). emptySlot: the index was inside and the slot there was never filled.

List is a doubly linked list: O(1) insertion and removal at both ends, O(n) access by index. It implements Iterable, Cloneable and array construction: List from [1, 2, 3], or List from values over any Array.

Member Returns Complexity Description
List.create() List O(1) An empty list.
count() Count O(1) Number of elements.
isEmpty() bool O(1) True when empty.
first() Element O(1) Throws ArrayError when empty.
last() Element O(1) Throws ArrayError when empty.
get(index) Element O(n) Throws ArrayError.indexOutOfBounds.
prepend(value Element) — O(1) Add to the front.
append(value Element) — O(1) Add to the back.
insert(at, value Element) — O(n) at may be 0 through count(). Past count() throws ArrayError.indexOutOfBounds.
removeFirst() Element O(1) Throws ArrayError when empty.
removeLast() Element O(1) Throws ArrayError when empty.
remove(at) Element O(n) Throws ArrayError.indexOutOfBounds.
clear() — O(n) Remove every element.
clone() List O(n) A deep copy. A copy of an element that is or holds a promise is E3141.
createIterator() ListIterator O(1) Throws IterationError.exhausted when empty.

ListIterator implements Iterator with Element: current() and advance().

The list’s throwing methods throw ArrayError.

typealias Score = int(i64.min to i64.max)
typealias ScoreList = List with Score
function main() returns ExitCode
let list = ScoreList.create()
list.append(2)
list.prepend(1)
try list.insert(2, value: 3) otherwise panic("index is within [0, count]")
let front = try list.removeFirst() otherwise 0
for value in list 'each'
print("{value} ")
end 'each'
print("\n{front} {list.count()}\n")
return 0
end 'main'

Output: 2 3 and 1 2.

Map is a hash table from keys to values. The key type must be Hashable and Equatable. Maps are built with create() or a dictionary literal ["a": 1, "b": 2], and iterate as (key, value) tuples in table order, which is unspecified and, for keys that hash through the process seed, differs from run to run. The seed’s resistance to keys chosen to collide covers String, Character and Array keys and keys whose hash() is built with Hasher; integer and float keys hash without it. The table resizes when it is three-quarters full.

Member Returns Description
Map.create() Map An empty map.
insert(key immutable Key, value Value) — Add a new entry. Throws MapError.keyAlreadyExists when the key is present.
upsert(key immutable Key, value Value) — Add the entry, or replace the value of an existing key.
get(key Key) Value Throws MapError.keyNotFound.
contains(key Key) bool Key test.
remove(key Key) bool Remove the entry; true when the key was present.
count() EntryCount Number of entries.
getCapacity() table capacity Total slots in the table: 0 for a map from create() until its first insert, 16 after that for a small map.
clone() Map An independent copy of every key and value; writing either map leaves the other unchanged. A map whose values are or hold promises is E3141.
createIterator() MapIterator Throws IterationError.exhausted when empty.

MapIterator implements Iterator with (Key, Value): current() and advance().

A key is stored in an immutable slot. A number, String or other value type needs nothing, a constant such as a b"..." literal is inserted as it is, and a record or array built at run time is freezed where it is inserted (counts.upsert(freeze ByteArray.create(3), value: 7)); an unfrozen one is E3207. A stored key is read-only: a key read back from the map, by iteration or otherwise, is immutable and takes no writes (E3197), so a key’s hash stays the one it was filed under, and it goes straight into an immutable holder with no copy. clone() gives a key to change.

enum MapError implements Error
keyNotFound
keyAlreadyExists
end 'MapError'
typealias Age = int(0 to 150)
typealias Ages = Map with String, Age
function main() returns ExitCode
let ages = Ages.create()
try ages.insert("ann", value: 30) otherwise panic("new key")
try ages.insert("ann", value: 31) otherwise 'duplicate'
print("ann is already present\n")
end 'duplicate'
ages.upsert("bob", value: 25)
ages.upsert("ann", value: 32)
let ann = try ages.get("ann") otherwise 0
print("{ann} {ages.contains("bob")} {ages.remove("bob")} {ages.count()}\n")
for (name, age) in ages 'each'
print("{name}: {age}\n")
end 'each'
return 0
end 'main'

Output: ann is already present, 32 true true 1, ann: 32.

Set is a hash set. The element type must be Hashable and Equatable. Build one with create(), Set from [1, 2, 3], or Set from values over any Array. Iteration order is unspecified and, for elements that hash through the process seed, differs from run to run. The seed’s resistance to elements chosen to collide covers String, Character and Array elements and elements whose hash() is built with Hasher; integer and float elements hash without it.

Member Returns Description
Set.create() Set An empty set.
insert(element immutable Element) — Add an element; inserting a present element does nothing.
contains(element Element) bool Membership test.
remove(element Element) bool Remove; true when the element was present.
count() MemberCount Number of elements.
getCapacity() table capacity Total slots in the table.
clone() Set An independent copy of every element; changing either set leaves the other unchanged.
createIterator() SetIterator Throws IterationError.exhausted when empty.

SetIterator implements Iterator with Element: current() and advance().

An element is stored in an immutable slot, as a Map key is: a value type needs nothing, and a record or array built at run time is freezed where it is inserted. An element read back from the set is immutable and takes no writes (E3197); clone() gives one to change. Set from values over an Array of value types takes any array; over elements that are not value types, the array holds immutable elements (Array with immutable Name).

typealias Tags = Set with String
function main() returns ExitCode
let tags = Tags.create()
tags.insert("red")
tags.insert("red")
tags.insert("blue")
print("{tags.count()} {tags.contains("red")} {tags.remove("red")} {tags.count()}\n")
return 0
end 'main'

Output: 2 true true 1.

Slot with T is a named place that holds one T or none. T is any type, a unique one included. A slot is an ordinary record, so it lives in a field and inside an isolated region.

type Job
export var n as ElementIndex
static function create(n ElementIndex) returns Self
return Self{n: n}
end 'create'
end 'Job'
typealias JobSlot = Slot with Job
function main() returns ExitCode
let slot = JobSlot.create("jobs")
slot.fill(Job.create(3))
print("{slot.isFull()} {slot.held().n}\n")
let job = slot.take()
print("{job.n} {slot.isEmpty()}\n")
return 0
end 'main'

Output: true 3 and 3 true.

Member Returns Description
Slot.create(name String) Slot An empty slot. name appears in the panic of a misuse.
isEmpty() / isFull() bool Whether the slot holds a value.
fill(item T) — Puts item in the slot. Panics naming the slot when it is full.
replace(item T) — Puts item in the slot whether or not it was full.
held() T Reads the value and leaves it in the slot. Panics naming the slot when it is empty.
take() T Moves the value out. Panics naming the slot when it is empty.
clear() — Empties the slot; an empty slot stays empty.

FixedArray is a fixed-size array whose element count is part of its type: FixedArray with 3 Coord holds exactly three elements, and countof(Vec3) is the constant 3. A FixedArray with Coord with no count is runtime-sized: its length is given to create(n). It implements Iterable. The growable array is Array.

Member Returns Description
FixedArray.create() FixedArray Every element zero; refused (E3106) for a managed element (a String, a record, an array or a union), for an element alias whose range excludes 0 and for an enum or union whose raw values include no 0. A pure call: discarding the result with _ = is E3064. A fixed array is one allocation at any size. Called through an alias that states a count (Vec3.create()); a length argument is E3194.
FixedArray.create(n) FixedArray Through a runtime-sized alias (typealias Buf = FixedArray with Coord): n zero elements in one allocation, n an ElementIndex. A constant n gives the sized type FixedArray with n Coord. The length is fixed at creation, so push and reserve are refused; an argument other than n and value:, or no n, is E3194.
FixedArray.create(value: v) FixedArray Through an alias that states a count (Vec3.create(value: v)): every element starts as v. The element may be a managed value, a ranged alias that excludes 0 or an enum whose raw values include no 0, which Vec3.create() refuses (E3106); each slot of a managed element holds its own reference to v. A length argument is E3194.
FixedArray.create(n, value: v) FixedArray Through a runtime-sized alias: n elements, each starting as v, in one allocation. Legal for an element with no zero value, as create(value: v) is. A constant n gives the sized type FixedArray with n Coord.
FixedArray from [a, b, c] FixedArray A literal; the count is the literal’s length, through a runtime-sized alias too.
count() Count The fixed size: answered from the type, and for a runtime-sized value read from the record’s length.
get(index) Element Throws ArrayError.indexOutOfBounds at or past the fixed size, unless the index is proven inside it.
set(index, value Element) — Throws ArrayError.indexOutOfBounds at or past the fixed size, unless the index is proven inside it.
refill(value Element) — Writes value into every element in place; the length is unchanged.
clone() FixedArray An independent copy. A fixed array of scalars shares its storage copy-on-write, which separates on the first write to either; a fixed array of managed elements clones each element.
createIterator() ArrayIterator Throws IterationError.exhausted when the fixed array is empty.

A fixed array’s length is set when it is built, by the count its type states or by create(n), and holds for its whole life; the members above are all it has.

An index the compiler proves inside 0 to N-1 makes get and set total: the call cannot throw, is written without try, and a try on it is E3055. A proven index is a constant, a value whose ranged type lies inside (typealias Slot = int(0 to 2) implements ElementIndex for a FixedArray with 3), the counter of a counted for loop between compile-time bounds inside the size, or a let computed from those. A constant index at or past the size is E3005. Any other index is checked at run time and needs try (E3057 without it), as every index into a runtime-sized fixed array is. See Fixed arrays.

typealias Coord = int(i64.min to i64.max)
typealias Vec3 = FixedArray with 3 Coord
function readOr(v Vec3, index ElementIndex, fallback Coord) returns Coord
return try v.get(index) otherwise fallback
end 'readOr'
function main() returns ExitCode
let v = Vec3.create()
v.set(1, value: 7)
for i in 0 upto countof(Vec3) 'fill'
v.set(i, value: v.get(i) + 1)
end 'fill'
let literal = FixedArray from [1, 2, 3]
var sum = 0 as Count
for x in literal 'each'
sum = sum + x
end 'each'
print("{v.count()} {countof(Vec3)} {v.get(1)} {readOr(v, index: 3, fallback: -1)} {sum}\n")
return 0
end 'main'

Output: 3 3 8 -1 6.

In a for header, start to end and start upto end compile to a counted loop with no allocation. Anywhere else they are values:

Expression Type Visits
start to end Range start through end, both included
start upto end OpenRange start up to but excluding end

Both implement Iterable with (RangeBound, RangeIterator); RangeBound is int(i64.min to i64.max).

Member Returns Description
Range.create(start RangeBound, finish RangeBound) Range The same as start to finish.
OpenRange.create(start RangeBound, endExclusive RangeBound) OpenRange The same as start upto endExclusive.
createIterator() RangeIterator Throws IterationError.exhausted for an empty range (finish < start, or endExclusive <= start).

RangeIterator implements Iterator with RangeBound and BidirectionalIterator:

Member Returns Description
RangeIterator.create(first RangeBound, last RangeBound) RangeIterator Both inclusive. Throws exhausted when last < first.
current() RangeBound The current value.
index() int(0 to u64.max) Steps taken from first.
advance() — Throws exhausted at last.
retreat() — Throws atStart at first.
function main() returns ExitCode
let inclusive = 1 to 4
var total = 0 as RangeBound
for x in inclusive 'sum'
total = total + x
end 'sum'
for (iter, x) in (10 upto 13).withIterator() 'each'
print("{iter.index()}:{x} ")
end 'each'
print("total={total}\n")
return 0
end 'main'

Output: 0:10 1:11 2:12 total=10.

A live iterator always points at a valid element, so current() cannot fail; navigation throws IterationError. createIterator() on an empty collection throws IterationError.exhausted instead of returning an iterator with nothing under it.

enum IterationError implements Error
exhausted
atStart
end 'IterationError'

exhausted: an advance past the last element. atStart: a retreat before the first. A failed move leaves the position unchanged.

ArrayIterator (what Array.createIterator(), Array.cursor() and FixedArray.createIterator() return) implements BidirectionalIterator with Element and adds random access:

Member Returns Throws Description
ArrayIterator.create(source) ArrayIterator IterationError Over raw array storage; exhausted when it is empty.
current() Element — The element at the position.
index() int(0 to u64.max) — The position.
advance() — IterationError Forward one; exhausted at the end.
retreat() — IterationError Back one; atStart at position 0.
seek(index) — IterationError Jump to an absolute position; exhausted when out of bounds.
peek(ahead) Element IterationError The element ahead positions on, without moving.
advanceBy(n IterStep) — IterationError Forward n (from Iterator).
retreatBy(n IterStep) — IterationError Back n (from BidirectionalIterator).

advanceBy and retreatBy step one at a time, so a move that fails part-way leaves the iterator where the throw happened. IterStep is unsigned: the direction is the method you call, so a negative step is refused at the argument door rather than read as a move the other way.

ArrayIterator.ElementMemory is the raw array storage that create takes.

typealias Score = int(i64.min to i64.max)
typealias ScoreArray = Array with Score
function main() returns ExitCode
let values = ScoreArray.create(0)
for i in 1 to 5 'fill'
values.push(i * 10)
end 'fill'
let c = try values.cursor() otherwise panic("not empty")
try c.advance() otherwise panic("has a second element")
let ahead = try c.peek(2) otherwise 0
print("{c.index()} {c.current()} {ahead}\n")
try c.advanceBy(3) otherwise panic("in range")
let beyond = try c.peek(1) otherwise -1
print("{c.current()} {beyond}\n")
return 0
end 'main'

Output: 1 20 40 and 50 -1.

Iterator Produced by Element
ListIterator List.createIterator() the list’s element
MapIterator Map.createIterator() (Key, Value)
SetIterator Set.createIterator() the set’s element
StringIterator String.createIterator() Character
RangeIterator Range/OpenRange.createIterator() RangeBound

Each has a static create, current() and advance(). The storage types an iterator’s signatures name are public aliases of it:

Iterator Public aliases
ListIterator EManagedList, the list’s raw chain, which create takes
MapIterator Entry, the (Key, Value) pair current() returns; IterKeyArray, IterValueArray and IterStateArray, the arrays of keys, values and slot states it scans
SetIterator IterElementArray and IterStateArray, the arrays of elements and slot states it scans

The protocols the library and the language are built on.

Interface Requirement Used by
Error none Every throwable type: enum E implements Error
Equatable function equals(other Self) returns bool ==, !=, contains
Comparable function compare(other Self) returns Ordering sort()
Hashable function hash() returns HashValue Map keys, Set elements
Cloneable function clone() returns Self clone()
Stringable function toString() returns String "{value}"
FormattedStringable function toString(format String) returns String "{value:format}" — the text after the colon is passed as format
Iterator with Element current() returns Element, advance(mutable self) throws IterationError iterators
BidirectionalIterator extends Iterator; retreat(mutable self) throws IterationError reversible iterators
Iterable with (Element, Iter) createIterator() returns Iter throws IterationError for-in
Parsable static fromString(input String) returns Self throws Error int.fromString and friends

The literal-initialization interfaces (InitableFromStringLiteral, InitableFromCharLiteral, InitableFromArrayLiteral, InitableFromDictionaryLiteral) let a type be written as MyType from <literal>; see Initializing From Literals in LANGUAGE_REFERENCE.md.

A type declares toString once, so it implements Stringable or FormattedStringable, not both.

enum Ordering
lessThan
equalTo
greaterThan
end 'Ordering'

HashValue is int(0 to u32.max); IterStep is int(0 to u64.max).

Function Returns Description
spreadHash(hash HashValue) HashValue Mix a hash’s bits (the MurmurHash3 32-bit finalizer). Map and Set apply it before choosing a slot, so keys with regular structure do not cluster. A hash() implementation does not need to call it.
On Method Returns Description
Iterator advanceBy(n IterStep) — Call advance() n times.
BidirectionalIterator retreatBy(n IterStep) — Call retreat() n times.
Iterable map(transform function(Element) returns Element) Array with Element Each element transformed.
Iterable filter(keep function(Element) returns bool) Array with Element The elements keep accepts.
Iterable containsWhere(predicate function(Element) returns bool) bool True when any element matches.
Iterable withIterator() iterator pairs Iterate as for (iter, element) in collection.withIterator(), with the iterator in hand.
typealias Cents = int(0 to u32.max)
type Money implements FormattedStringable, Equatable, Comparable, Hashable, Cloneable
let cents as Cents
static function create(cents Cents) returns Money
return Money{cents: cents}
end 'create'
function toString(format String) returns String
return "{format} {cents}"
end 'toString'
function equals(other Money) returns bool
return cents == other.cents
end 'equals'
function compare(other Money) returns Ordering
return cents.compare(other.cents)
end 'compare'
function hash() returns HashValue
return cents.hash()
end 'hash'
function clone() returns Money
return Money{cents: cents}
end 'clone'
end 'Money'
typealias Prices = Set with Money
function main() returns ExitCode
let price = Money.create(250)
let prices = Prices.create()
prices.insert(price)
prices.insert(price.clone())
print("{price:EUR} | {price:USD} | {price == Money.create(250)} {price.compare(Money.create(1))} {prices.count()}\n")
return 0
end 'main'

Output: EUR 250 | USD 250 | true greaterThan 1.