Arrays
const names: string[] = ["Ada", "Linus"];
const first: string = names[0]; // "Ada"
const count: usize = names.length; // 2
let statuses: Array<i32> = [200, 201];
statuses[1] = 204; // [200, 204]
statuses.push(202); // [200, 204, 202]
const successful: boolean = statuses.includes(200); // true
const page: i32[] = statuses.slice(0, 2); // [200, 204]
const immutableReverse: i32[] = statuses.toReversed(); // [202, 204, 200]Both T[] and Array<T> are accepted. Indexed reads and writes perform runtime bounds checks. Mutating methods require a let receiver. length reports the element count, while capacity is a read-only tyrus extension exposing reserved native storage.
Array literals and repeated values
The type [T; N] declares an array with exactly N elements. Initialize it with a list containing exactly N values or with [value; N] to repeat one value. Array literals without a fixed-size annotation, such as T[], remain dynamically sized.
const repeated: [i32; 5] = [0; 5];
const values: [i32; 5] = [1, 2, 3, 4, 5];
print(repeated); // [0, 0, 0, 0, 0]
print(values); // [1, 2, 3, 4, 5]error
const most: [u8; 3] = [10, 20, 30, 40]; error[E0308]: fixed-length type requires 3 elements, but this initializer contains 4
at /src/main.tyr:1:23
const most: [u8; 3] = [10, 20, 30, 40];
^^^^^^^^^^^^^^^^
help: provide exactly 3 elements in this initializerArrays built by a run of push
A local array that starts empty and is filled by a straight run of push is compiled as the array literal it is equivalent to, which lets it live on the stack instead of the heap:
function build(seed: i32): i32[] {
let values: i32[] = [];
values.push(seed);
values.push(seed + 1);
values.push(seed + 2);
return values;
}The rewrite is exact, same elements, same order, same length, and the array still grows afterwards. It applies only while nothing can have observed the array in between: the run stops at the first statement that is not a push onto that array, an element that reads the array being built is never moved ahead of it, and a spread element disqualifies the run because it contributes an unknown number of elements. Element types are limited to those copied by value.
Nothing about this is visible in behaviour, only in how much the program allocates. Growing an array otherwise allocates even in a release build, since the growth is a call the optimizer cannot look inside.
Bounds checks a loop already proved
Every indexed read and write is checked at run time, except where a surrounding loop already proved the check cannot fail. In the counting shape below the body is only reached when i < values.length, and nothing between that test and the element access can change either side of it, so the comparison the access would emit is the loop condition written a second time:
function sweep(values: i32[]): i32 {
let sum = 0;
for (let i: usize = 0; i < values.length; i += 1) {
sum += values[i];
}
return sum;
}The proof is deliberately narrow, because being wrong about it removes the only thing standing between a bad index and a read outside the buffer. A loop qualifies only when the counter is declared by its own init from a non-negative literal, the condition is exactly counter < array.length, the update only increases the counter by a constant, the array is a local, a parameter, or a const global nothing can grow, and, inside the body, the array is never used for anything but indexing and length while the counter is never written. Anything else keeps its check: a push in the body, an index other than the counter, a rebinding of either name, or a mention of either from inside a closure.
A check that is kept behaves exactly as it always did, naming the offending index and the array's length on stderr before exiting non-zero.
Bounds checks a fixed table already proved
A loop is not the only thing that can settle an index. When a binding is declared const from an array literal, its element count is written in the source, and a literal index below that count is in range with no loop involved:
readonly const PRIMES: i32[] = [2, 3, 5, 7, 11, 13, 17, 19];
function third(): i32 {
return PRIMES[2];
}The check for PRIMES[2] is dropped, and an index past the end is a compile error rather than a runtime one, PRIMES[8] is rejected with E0606, naming the valid range. What fixes the length is const, not the annotation: the binding cannot be reassigned, and a mutating method on it is rejected. readonly const is how a fixed table is normally written, but a plain const array literal proves the same thing.
The binding also has to be read and nothing else. Passing it to a function, capturing it in a closure, or calling any method on it ends the proof and the check stays, the same narrow rule the loop shape follows, and for the same reason.
Mutating methods require let
A const array is deeply immutable. Calling push, sort, reverse, or other mutating methods on a const array is a compile error.
error
const fixed: i32[] = [1, 2, 3];
fixed.push(4); error[E0384]: cannot call mutating method `push` on immutable array `fixed`
at /src/main.tyr:3:1
fixed.push(4);
^^^^^
help: declare the binding with `let` to allow assignmentProperties
| Member | Type | Behavior |
|---|---|---|
length | usize | Current number of elements. |
capacity | usize | Reserved native storage; this is a Tyrus extension. |
Mutable methods
These methods change the array and therefore require a mutable let binding. pop() and shift() return T?, so an empty array produces absence.
| Method | Signature | Behavior |
|---|---|---|
push | push(...items: T[]): usize | Appends values and returns the new length. |
pop | pop(): T? | Removes and returns the last value, or absence. |
unshift | unshift(...items: T[]): usize | Prepends values and returns the new length. |
shift | shift(): T? | Removes and returns the first value, or absence. |
splice | splice(start: i64, deleteCount?: i64, ...items: T[]): T[] | Removes, replaces, or inserts values and returns the removed values. |
sort, reverse, rotate, fill, and copyWithin also mutate the receiver. Their behavior is covered in Functional Methods.
Static methods
| Method | Signature | Behavior |
|---|---|---|
Array.of | Array.of(...items: T[]): T[] | Creates an array from its arguments. |
Array.from | Array.from(items: T[]): T[] | Copies an array into a dynamically sized array. |
Array.withCapacity | Array.withCapacity(capacity: usize): T[] | Creates an empty array with reserved capacity. |
Array.isArray | Array.isArray(value: unknown): boolean | Checks whether a value is an array. |
Functional Methods
| Category | Methods |
|---|---|
| Iteration & Transformation | map(), filter(), partition(), reduce(), reduceRight(), forEach() |
| Windowing & Matrices | windows(), scan(), cartesianProduct(), zip(), transpose() |
| Deduplication & Grouping | unique(), uniqueBy(), groupBy() |
| Toggle | toggle(), toggleAll() |
| Search & Test | find(), findLast(), findIndex(), findLastIndex(), some(), every(), includes(), equals(), indexOf(), lastIndexOf() |
| Flatten & Reorder | flat(), flatMap(), sort(), toSorted(), sortby(), sortedby(), reverse(), rotate(), toReversed(), random(), shuffle(), sample() |
| Slicing | slice(), splitAt() |
| Aggregation | sum(), product(), avg(), sumBy(), avgBy(), count(), concat(), join() |
| Mutation | splice(), fill(), copyWithin() |
| Access & Iteration | first(), last(), at(), keys(), values(), entries() |
| Immutable Copy | with() |
Iteration & Transformation
Predicate-based methods (filter, partition, some, every, find, findLast, findIndex, findLastIndex, uniqueBy, and groupBy) accept either an explicit arrow callback or an implicit expression such as value > 2; the element type is inferred from the receiver array.
map()
Creates a new array by applying a transformation callback to every element.
map<U>(callback: (element: T, index?: i64) => U): U[]const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: f64[] = prices.map(price => price * 1.08);
// [10.7892, 21.5892, 32.3892]error
const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: string[] = prices.map(price => price * 1.08); error[E0308]: type mismatch for `withTax`: expected `string[]`, found `f64[]`
at /src/main.tyr:2:7
const withTax: string[] = prices.map(price => price * 1.08);
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`filter()
Selects elements that satisfy a predicate.
filter(predicate: (element: T) => boolean): T[]const scores: i32[] = [85, 42, 91, 38, 76, 55];
const passing: i32[] = scores.filter(score => score >= 60);
// [85, 91, 76]error
const scores: i32[] = [85, 42, 91, 38, 76, 55];
const result: i32[] = scores.filter(score => score * 2); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:46
const result: i32[] = scores.filter(score => score * 2);
^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`partition()
Splits the elements into two stable arrays according to a predicate. The first array contains matching elements; the second contains the remaining elements. The receiver is not mutated.
partition(predicate: (element: T) => boolean): [T[], T[]]partition(field: string): [T[], T[]]partition(field: string, ...values: string[]): [T[], T[]]const values: i32[] = [1, 2, 3, 4];
const [evenValues, oddValues] = values.partition(value % 2 === 0);
print(evenValues); // [2, 4]
print(oddValues); // [1, 3]
print(values); // [1, 2, 3, 4]Object arrays can use a boolean field name directly, or a string field followed by one or more matching values. Field names are checked against the element type at compile time.
interface Ticket {
title: string;
completed: boolean;
category: string;
}
const tickets: Ticket[] = [
{ title: "Plan", completed: true, category: "work" },
{ title: "Read", completed: false, category: "learning" },
{ title: "Review", completed: true, category: "work" },
{ title: "Archive", completed: false, category: "personal" }
];
const [completed, pending] = tickets.partition("completed");
print(completed); // [{ title: "Plan", completed: true, category: "work" }, { title: "Review", completed: true, category: "work" }]
print(pending); // [{ title: "Read", completed: false, category: "learning" }, { title: "Archive", completed: false, category: "personal" }]
const [focused, deferred] = tickets.partition("category", "work", "learning");
print(focused); // [{ title: "Plan", completed: true, category: "work" }, { title: "Read", completed: false, category: "learning" }, { title: "Review", completed: true, category: "work" }]
print(deferred); // [{ title: "Archive", completed: false, category: "personal" }]An unknown field is rejected at compile time.
error
interface Ticket {
completed: boolean;
}
const tickets: Ticket[] = [{ completed: true }];
const [completed, pending] = tickets.partition("archived"); error[E0609]: `partition` key `archived` is not a field of `Ticket`
at /src/main.tyr:6:30
const [completed, pending] = tickets.partition("archived");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeFor more complex predicates, use an explicit arrow function. It can receive the element, its index, and the original array:
const readings: i32[] = [1, 2, 3, 4, 5, 6, 7, 8];
const [selected, remaining] = readings.partition((reading, index) => {
return reading > 1 && index < 3;
});
print(selected); // [2, 3]
print(remaining); // [1, 4, 5, 6, 7, 8]
print(readings); // [1, 2, 3, 4, 5, 6, 7, 8]partition() evaluates the predicate once per element and preserves the original order inside both output arrays. As with count(), a plain expression with exactly one free identifier is treated as an implicit per-element predicate; an explicit arrow function remains available for more complex cases. For memory safety, T must be Copy, string, or an object whose fields are Copy or string.
reduce()
Accumulates elements into a single value, from left to right.
reduce<U>(callback: (accumulator: U, element: T) => U, initial: U): Uconst values: i32[] = [10, 20, 30, 40];
const total: i32 = values.reduce((sum, value) => sum + value, 0);
// 100error
const values: i32[] = [10, 20, 30, 40];
const total: i64 = values.reduce((sum, value) => sum + value, 0); error[E0308]: type mismatch for `total`: expected `i64`, found `i32`
at /src/main.tyr:2:7
const total: i64 = values.reduce((sum, value) => sum + value, 0);
^^^^^
help: `i32` does not convert to `i64` on its own; write the conversion explicitly with `as i64`reduceRight()
Accumulates elements into a single value, from right to left.
reduceRight<U>(callback: (accumulator: U, element: T) => U, initial: U): Uconst letters: string[] = ["a", "b", "c", "d"];
const reversed: string = letters.reduceRight(
(acc, letter) => acc + letter, "",
);
// "dcba"error
const letters: string[] = ["a", "b", "c", "d"];
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, ""); error[E0308]: type mismatch for `reversed`: expected `i64`, found `string`
at /src/main.tyr:2:7
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, "");
^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`forEach()
Executes a callback for each element. The return value is discarded.
forEach(callback: (element: T) => void): voidconst colors: string[] = ["red", "green", "blue"];
colors.forEach(color => print(color));
// red
// green
// blueerror
const colors: string[] = ["red", "green", "blue"];
colors.forEach((color: i32) => print(color)); error[E0308]: type mismatch for callback parameter `color` of `forEach`: expected `string`, found `i32`
at /src/main.tyr:2:24
colors.forEach((color: i32) => print(color));
^^^
help: change the callback parameter type to `string`Search & Test
find()
Returns the first element matching a predicate, or absence if none match.
find(predicate: (element: T) => boolean): T?const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string? = users.find(name => name.startsWith("G"));
// "Grace"error
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string = users.find(name => name.startsWith("G")); error[E0003]: `match` is a reserved keyword in tyrus and cannot be used as an identifier
at /src/main.tyr:2:7
const match: string = users.find(name => name.startsWith("G"));
^^^^^
help: rename `match` to an identifier that is not a reserved keywordfindLast()
Returns the last element matching a predicate, or absence if none match.
findLast(predicate: (element: T) => boolean): T?const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string? = users.findLast(name => name.startsWith("G"));
// "Gordon"error
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string = users.findLast(name => name.startsWith("G")); error[E0308]: type mismatch for `last`: expected `string`, found `string?`
at /src/main.tyr:2:7
const last: string = users.findLast(name => name.startsWith("G"));
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`findIndex()
Returns the index of the first matching element, or -1.
findIndex(predicate: (element: T) => boolean): i64const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item === "banana");
// 1error
const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item.length); error[E0308]: type mismatch for `return`: expected `boolean`, found `usize`
at /src/main.tyr:2:44
const index: i64 = items.findIndex(item => item.length);
^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`findLastIndex()
Returns the index of the last matching element, or -1.
findLastIndex(predicate: (element: T) => boolean): i64const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n === 2);
// 3error
const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:52
const lastIdx: i64 = duplicates.findLastIndex(n => n);
^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`some()
Checks if at least one element satisfies a condition.
some(predicate: (element: T) => boolean): booleanconst ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age < 18);
// trueerror
const ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age * 2); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:44
const hasMinor: boolean = ages.some(age => age * 2);
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`every()
Checks if all elements satisfy a condition.
every(predicate: (element: T) => boolean): booleanconst temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t >= 36.0 && t <= 37.5);
// trueerror
const temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t + 1); error[E0369]: operator `+` cannot be applied to `f64` and `integer literal`
at /src/main.tyr:2:52
const allNormal: boolean = temperatures.every(t => t + 1);
^^^^^includes()
Checks if a specific value exists in the array.
includes(value: T): booleanconst fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes("banana");
// trueerror
const fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes(42); error[E0308]: type mismatch for `includes`: expected `string`, found `integer literal`
at /src/main.tyr:2:28
const hasBanana: boolean = fruits.includes(42);
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`equals()
Compares two arrays element by element: the same length, the same elements, in the same order. === and !== do not compare arrays; the compiler reports E0369 and points here.
equals(other: T[]): booleanconst left: i32[] = [1, 2, 3];
const right: i32[] = [1, 2, 3];
const same: boolean = left.equals(right);
// true
const reordered: boolean = left.equals([3, 2, 1]);
// falseerror
const grid: i32[][] = [[1], [2]];
const same: boolean = grid.equals([[1], [2]]); error[E0277]: array method `equals` compares arrays of numbers, `boolean`, `char` or `string`, but the elements are `i32[]`
at /src/main.tyr:2:23
const same: boolean = grid.equals([[1], [2]]);
^^^^^^^^^^^^^^^^^^^^^^^indexOf()
Returns the first index of a value, or -1 if not found.
indexOf(value: T, fromIndex?: i64): i64const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf(2);
// 1error
const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf("2"); error[E0308]: type mismatch for `indexOf`: expected `i32`, found `string`
at /src/main.tyr:2:20
const first: i64 = digits.indexOf("2");
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`lastIndexOf()
Returns the last index of a value, or -1 if not found.
lastIndexOf(value: T, fromIndex?: i64): i64const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf(2);
// 3error
const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf("2"); error[E0308]: type mismatch for `lastIndexOf`: expected `i32`, found `string`
at /src/main.tyr:2:19
const last: i64 = digits.lastIndexOf("2");
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Windowing, Scanning, and Matrix Operations
windows()
windows(size) returns overlapping copies of size consecutive elements. The receiver is unchanged; windows(0) is rejected and a size greater than the array length returns an empty array.
const readings: i32[] = [2, 4, 6, 8];
const windows: i32[][] = readings.windows(3); // [[2, 4, 6], [4, 6, 8]]
print(windows);scan()
scan(initial, callback) returns the initial accumulator followed by each accumulated value. The callback receives the accumulator and the current element, and the receiver is unchanged.
const values: i32[] = [2, 3, 4];
const totals: i32[] = values.scan(0, (total, value) => total + value); // [0, 2, 5, 9]
print(totals);cartesianProduct()
cartesianProduct(other) returns pairs in lexicographic receiver/argument order. Either empty input produces an empty result, and the receiver is unchanged.
const left: i32[] = [1, 2];
const right: i32[] = [10, 20];
const pairs: [i32, i32][] = left.cartesianProduct(right); // [[1, 10], [1, 20], [2, 10], [2, 20]]
print(pairs);zip()
zip(other) interleaves the receiver and the argument into an array of pairs, (T, U)[], where T is the receiver element type and U is the argument element type. The result length equals both inputs, which must match; the source arrays are left unchanged.
const names: string[] = ["ana", "bia"];
const scores: i32[] = [30, 25];
try {
const pairs: [string, i32][] = names.zip(scores); // [["ana", 30], ["bia", 25]]
print(pairs);
} catch (error: ZipError) {
print(error.code);
}A length mismatch throws a recoverable ZipError (code ERR_ARRAY_ZIP_MISMATCH) instead of aborting, so the call must be covered by a catch or by a throws ZipError clause on the enclosing function:
const names: string[] = ["ana", "bia"];
const scores: i32[] = [30];
try {
const pairs: [string, i32][] = names.zip(scores);
print(pairs.length);
} catch (error: ZipError) {
print(error.code); // ERR_ARRAY_ZIP_MISMATCH
}transpose()
transpose() converts a rectangular matrix into columns. Empty matrices and matrices with zero-width rows return empty arrays; irregular rows fail before a partial result is produced.
const matrix: i32[][] = [[1, 2], [3, 4], [5, 6]];
const columns: i32[][] = matrix.transpose(); // [[1, 3, 5], [2, 4, 6]]
print(columns);unique()
unique() returns the first occurrence of every distinct value in input order. It does not mutate the receiver and uses the native equality policy for strings and numbers.
const values: i32[] = [3, 1, 3, 2, 1];
const distinct: i32[] = values.unique(); // [3, 1, 2]
print(distinct);uniqueBy()
uniqueBy(selector) keeps the first element for each distinct hashable key. The selector can be a field name for object elements, an explicit callback, or an implicit expression where the element is inferred automatically.
const values: i32[] = [1, 2, 3, 4, 5];
const oddAndEven: i32[] = values.uniqueBy(value => value % 2); // [1, 2]
const oddAndEvenImplicit: i32[] = values.uniqueBy(value % 2); // [1, 2]
print(oddAndEven);groupBy()
groupBy(selector) creates a map from each hashable key to an array of elements in their original order. The selector can be a field name for object elements, an explicit callback, or an implicit expression where the element is inferred automatically. The first implementation requires Copy elements so each group owns its values safely.
const values: i32[] = [1, 2, 3, 4];
const groups: Map<i32, i32[]> = values.groupBy(value => value % 2); // { 1: [1, 3], 0: [2, 4] }
const groupsImplicit: Map<i32, i32[]> = values.groupBy(value % 2); // { 1: [1, 3], 0: [2, 4] }
print(groups.keys());Flatten & Reorder
flat()
Flattens nested arrays by one level.
flat(): T[]const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: i32[] = matrix.flat();
// [1, 2, 3, 4, 5]error
const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: string[] = matrix.flat(); error[E0308]: type mismatch for `flat`: expected `string[]`, found `i32[]`
at /src/main.tyr:2:7
const flat: string[] = matrix.flat();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`flatMap()
Maps each element to an array, then flattens the result by one level.
flatMap<U>(callback: (element: T) => U[]): U[]const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence.split(" "));
// ["hello", "world", "goodbye", "moon"]error
const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence); error[E0308]: `flatMap` callback must return an array, found `string`
at /src/main.tyr:2:25
const words: string[] = sentences.flatMap(sentence => sentence);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`sort()
Sorts the array in place using a comparison function.
sort(compare?: (left: T, right: T) => i32): thislet numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left - right);
// [4, 8, 15, 23, 42]error
let numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left < right); error[E0308]: type mismatch for `return`: expected `i32`, found `boolean`
at /src/main.tyr:2:31
numbers.sort((left, right) => left < right);
^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`toSorted()
Returns a new sorted copy without mutating the original.
toSorted(compare?: (left: T, right: T) => i32): T[]const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left - right);
// [4, 8, 15, 23, 42]
// original is unchangederror
const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left > right); error[E0308]: type mismatch for `return`: expected `i32`, found `boolean`
at /src/main.tyr:2:58
const sorted: i32[] = original.toSorted((left, right) => left > right);
^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`sortBy()
Sorts an array in place by a statically resolved field. The key must be a string literal naming a numeric, boolean, character, or string field. The optional second argument controls the order: it defaults to ascending and accepts "desc" for descending order.
sortBy(key: keyof T, order?: "asc" | "desc"): thisinterface Score {
name: string;
points: i32;
}
let scores: Score[] = [
{ name: "Ada", points: 30 },
{ name: "Grace", points: 10 },
{ name: "Linus", points: 20 },
];
scores.sortBy("points"); // [{ name: "Grace", points: 10 }, { name: "Linus", points: 20 }, { name: "Ada", points: 30 }]
scores.sortBy("points", "desc"); // [{ name: "Ada", points: 30 }, { name: "Linus", points: 20 }, { name: "Grace", points: 10 }]The field is resolved at compile time, so the generated stable merge-sort loop reads the field directly without runtime reflection. sortBy() requires a mutable let receiver and runs in O(n log n) time with O(n) auxiliary space.
sortedBy()
Returns a sorted copy by a statically resolved field and leaves the receiver unchanged. Its optional second argument defaults to ascending and accepts "desc" for descending order. The first version requires the element fields to be Copy, preventing an unsafe shallow copy of owned values. It uses stable O(n log n) merge sort with O(n) auxiliary space.
sortedBy(key: keyof T, order?: "asc" | "desc"): T[]interface Coordinate {
x: i32;
y: i32;
}
const points: Coordinate[] = [
{ x: 3, y: 9 },
{ x: 1, y: 4 },
{ x: 2, y: 7 },
];
const byX: Coordinate[] = points.sortedBy("x"); // [{ x: 1, y: 4 }, { x: 2, y: 7 }, { x: 3, y: 9 }]
const byYDesc: Coordinate[] = points.sortedBy("y", "desc"); // [{ x: 3, y: 9 }, { x: 2, y: 7 }, { x: 1, y: 4 }]reverse()
Reverses the array in place.
reverse(): thislet stack: i32[] = [1, 2, 3];
stack.reverse();
// [3, 2, 1]error
const stack: i32[] = [1, 2, 3];
stack.reverse(); error[E0384]: cannot call mutating method `reverse` on immutable array `stack`
at /src/main.tyr:2:1
stack.reverse();
^^^^^
help: declare the binding with `let` to allow assignmentrotate()
Rotates the array in place. Positive amounts rotate to the left; negative amounts rotate to the right. The amount is normalized by the array length, and empty or single-element arrays are unchanged.
rotate(amount: i64): thislet values: i32[] = [1, 2, 3, 4, 5];
values.rotate(2); // [3, 4, 5, 1, 2]
values.rotate(-1); // [2, 3, 4, 5, 1]rotate() requires a mutable let receiver and runs in O(n) time with O(1) auxiliary space, without allocating a second array.
toReversed()
Returns a new reversed copy without mutating the original.
toReversed(): T[]const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: string[] = days.toReversed();
// ["Wed", "Tue", "Mon"]
// days is unchangederror
const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: i32[] = days.toReversed(); error[E0308]: type mismatch for `reversed`: expected `i32[]`, found `string[]`
at /src/main.tyr:2:7
const reversed: i32[] = days.toReversed();
^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`random()
Returns a uniformly selected T. An empty array aborts at runtime.
random(): Tconst fruits = ["grape", "banana", "orange", "strawberry"];
const chosen = fruits.random();
print(chosen); // "orange"error
const fruits: string[] = [];
const chosen = fruits.random(); error[E0606]: array.random requires at least 1 element(s), found 0
at /src/main.tyr:2:16
const chosen = fruits.random();
^^^^^^shuffle()
Returns a new uniformly shuffled array without mutating the receiver. Arrays with fewer than two elements abort at runtime.
shuffle(): T[]const fruits = ["grape", "banana", "orange", "strawberry"];
const shuffled = fruits.shuffle();
print(shuffled); // ["banana", "strawberry", "grape", "orange"]error
const value = [1];
const shuffled = value.shuffle(); error[E0606]: array.shuffle requires at least 2 element(s), found 1
at /src/main.tyr:2:18
const shuffled = value.shuffle();
^^^^^sample()
Returns a new array with count uniformly selected elements. count must be between 1 and the receiver length, inclusive. Without options, source positions do not repeat. { repeat: true } permits repeated positions but does not guarantee them.
sample(count: usize, options?: { repeat?: boolean }): T[]const teams = ["Arsenal", "Barcelona", "Bayern Munich", "Inter Milan"];
const distinct = teams.sample(2);
const independent = teams.sample(2, { repeat: true });
print(distinct); // ["Bayern Munich", "Barcelona"]
print(independent); // ["Inter Milan", "Inter Milan"]error
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const none = teams.sample(0); error[E0606]: sample count 0 is out of bounds: valid counts are 1 to 3 (length 3)
at /src/main.tyr:2:27
const none = teams.sample(0);
^error
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const tooMany = teams.sample(4); error[E0606]: sample count 4 is out of bounds: valid counts are 1 to 3 (length 3)
at /src/main.tyr:2:30
const tooMany = teams.sample(4);
^Slicing
slice()
Extracts a copy of a contiguous subarray.
slice(start?: i64, end?: i64): T[]const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: string[] = letters.slice(1, 4);
// ["b", "c", "d"]error
const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: i32[] = letters.slice(1, 4); error[E0308]: type mismatch for `middle`: expected `i32[]`, found `string[]`
at /src/main.tyr:2:7
const middle: i32[] = letters.slice(1, 4);
^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Indexing with a Range is sugar for .slice(): arr[a..b] is arr.slice(a, b), and every open-ended form works too, arr[a..], arr[..b], arr[..=b], and the full-range arr[..]. Like .slice() itself, this always copies into a new array; tyrus arrays have no zero-copy borrowed-slice representation yet.
const letters: string[] = ["a", "b", "c", "d", "e"];
print(letters[1..4]);
// ["b", "c", "d"] same as letters.slice(1, 4)
print(letters[1..=3]);
// ["b", "c", "d"] inclusive of index 3
print(letters[2..]);
// ["c", "d", "e"]
print(letters[..3]);
// ["a", "b", "c"]
print(letters[..]);
// ["a", "b", "c", "d", "e"]splitAt()
Splits the array into two arrays at a given index.
splitAt(index: i64): [T[], T[]]const letters: string[] = ["a", "b", "c", "d", "e"];
const parts: [string[], string[]] = letters.splitAt(2);
// [["a", "b"], ["c", "d", "e"]]error
const letters: string[] = ["a", "b"];
const parts: [string[], string[]] = letters.splitAt(10); error[E0606]: splitAt index 10 is out of bounds: valid indices are 0 to 2 (length 2)
at /src/main.tyr:2:53
const parts: [string[], string[]] = letters.splitAt(10);
^^splitAt always returns two ordinary, dynamically sized arrays ([T[], T[]]), including when called on a fixed-size array. index may equal the array's length, yielding an empty second half, but a larger index is a compile error when the array's length is statically known, and a runtime abort otherwise.
Aggregation
count()
Returns the length, or counts occurrences of a value or predicate match.
count(value?: T | (element: T) => boolean): i64const numbers: i32[] = [1, 2, 3, 4, 5, 6];
print(numbers.count()); // 6
print(numbers.count(3)); // 1
print(numbers.count(value % 2 === 0)); // 3
print(numbers.count(value > 3)); // 3error
const numbers: i32[] = [1, 2, 3, 4, 5, 6];
const total: i64 = numbers.count(value => value.toString()); error[E0282]: cannot infer type of parameter `value`
at /src/main.tyr:2:43
const total: i64 = numbers.count(value => value.toString());
^^^^^
error[E0599]: no method named `toString` for type `<inferred>`
at /src/main.tyr:2:43
const total: i64 = numbers.count(value => value.toString());
^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type
error[E0308]: `count` expects a value assignable to `i32`, found `(<inferred>) => void`
at /src/main.tyr:2:34
const total: i64 = numbers.count(value => value.toString());
^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`
error[E0308]: type mismatch for `total`: expected `i64`, found `usize`
at /src/main.tyr:2:7
const total: i64 = numbers.count(value => value.toString());
^^^^^
help: `usize` does not convert to `i64` on its own; write the conversion explicitly with `as i64`count() returns the length; count(value) counts elements equal to value; count(condition), a plain expression referencing exactly one identifier not already declared in the current scope, is promoted to an implicit per-element condition, sugar for count((implicitParam): boolean => condition) with no arrow function to write. An identifier that already resolves in scope is not free, so the expression is checked as an ordinary count(value) call instead, comparing its (constant) boolean result against the element type is a compile error naming the identifier that shadowed the implicit parameter. An expression referencing more than one undeclared identifier is also a compile error, since the sugar only ever introduces one implicit parameter.
sum()
Returns the sum of all numeric elements using the array's element type. An empty numeric array returns that type's zero value.
sum(): Tconst values: i32[] = [2, 3, 4];
const total = values.sum(); // inferred as i32
print(total); // 9
const empty: i32[] = [];
print(empty.sum()); // 0sum() is rejected for non-numeric element types and is compiled as a direct native loop without a callback or per-element runtime dispatch.
product()
Returns the product of all numeric elements using the array's element type. An empty numeric array returns that type's one value.
product(): Tconst values: i32[] = [2, 3, 4];
const product = values.product(); // inferred as i32
print(product); // 24
const empty: i32[] = [];
print(empty.product()); // 1product() follows the same numeric-type and native-loop rules as sum().
avg()
Returns the arithmetic average of numeric elements. Integer, f32, and f64 arrays return f64?; f128 arrays return f128?. An empty array produces absence.
avg(): f64? | f128?const values: i32[] = [2, 3, 4];
const average = values.avg(); // inferred as f64?
print(average ?? 0.0); // 3.0
const empty: i32[] = [];
print(empty.avg() ?? 0.0); // 0.0The optional result must be handled with ??, narrowing, or another valid optional operation before direct numeric use.
sumBy()
Returns the sum of a numeric field across all elements. The key must be a string literal naming a numeric field.
sumBy(key: string): T[K]interface Item {
name: string;
quantity: i32;
price: f64;
}
const items: Item[] = [
{ name: "Widget", quantity: 3, price: 25.0 },
{ name: "Gadget", quantity: 1, price: 99.99 }
];
const totalQuantity = items.sumBy("quantity"); // 4 (i32)
const totalPrice = items.sumBy("price"); // 124.99 (f64)avgBy()
Returns the arithmetic average of a numeric field across all elements. The key must be a string literal naming a numeric field. Always returns f64? (or f128? for f128 fields).
avgBy(key: string): f64? | f128?const items: Item[] = [
{ name: "Widget", quantity: 3, price: 25.0 },
{ name: "Gadget", quantity: 1, price: 99.99 }
];
const avgPrice = items.avgBy("price"); // 62.495 (f64?)concat()
Merges two arrays into a new one.
concat(...items: (T | T[])[]): T[]const front: i32[] = [1, 2];
const back: i32[] = [3, 4];
const merged: i32[] = front.concat(back);
// [1, 2, 3, 4]error
const front: string[] = ["a", "b"];
const merged: string[] = front.concat(42); error[E0308]: type mismatch for `concat`: expected `string[]`, found `integer literal`
at /src/main.tyr:2:26
const merged: string[] = front.concat(42);
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`join()
Joins all elements into a single string using a separator.
join(separator: string): stringconst parts: string[] = ["tyrus", "is", "native"];
const sentence: string = parts.join(" ");
// "tyrus is native"error
const numbers: i32[] = [1, 2, 3];
const text: string = numbers.join(", "); error[E0277]: `join` currently requires a `string[]` receiver
at /src/main.tyr:2:22
const text: string = numbers.join(", ");
^^^^^^^^^^^^^^^^^^Mutation
splice()
Removes, replaces, or inserts elements in place.
splice(start: i64, deleteCount?: i64, ...items: T[]): T[]let values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8);
print(values[1]);
print(removed[0]);error
const values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8); error[E0384]: cannot call mutating method `splice` on immutable array `values`
at /src/main.tyr:2:24
const removed: i32[] = values.splice(1, 2, 7, 8);
^^^^^^
help: declare the binding with `let` to allow assignmentsplice(start, deleteCount?, ...items) mutates the receiver and returns a new array containing the removed elements. Negative starts count from the end, deletion is clamped to the available range, and inserted values must match the array element type.
fill()
Replaces all elements with a fixed value.
fill(value: T): thislet buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill(7);
// [7, 7, 7, 7, 7]error
let buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill("x"); error[E0308]: type mismatch for `fill`: expected `i32`, found `string`
at /src/main.tyr:2:1
buffer.fill("x");
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`copyWithin()
Copies a contiguous section of the array to another position in the same array.
copyWithin(target: i64, start: i64, end?: i64): thislet data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin(0, 3);
// [4, 5, 3, 4, 5]error
let data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin("x", 3); error[E0308]: type mismatch for `copyWithin`: expected `i64`, found `string`
at /src/main.tyr:2:1
data.copyWithin("x", 3);
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Access & Iteration
first()
Returns the first element as T?. An empty array produces absence. The type annotation is optional: when values is i32[], tyrus infers i32? automatically. Optional<i32> is the equivalent explicit spelling.
first(): T?const values: i32[] = [10, 20, 30];
const firstValue = values.first(); // inferred as i32?
const explicitFirst: Optional<i32> = values.first();
if (firstValue) {
print(firstValue + 1); // 11
}
const firstOrDefault: i32 = firstValue ?? 0;
print(firstOrDefault);
const empty: i32[] = [];
print(empty.first() ?? -1); // -1T? is intentional: first() returns one value, not a collection, and remains O(1) without allocating an empty result array. Direct use as i32 is rejected until an if, ??, ternary, optional chaining, or another valid narrowing operation handles absence.
last()
Returns the last element as T?. An empty array produces absence, and tyrus infers the optional element type automatically when the annotation is omitted.
last(): T?const values: i32[] = [10, 20, 30];
const lastValue = values.last(); // inferred as i32?
const explicitLast: Optional<i32> = values.last();
const lastOrDefault: i32 = lastValue ? lastValue : 0;
print(lastOrDefault);
const empty: i32[] = [];
print(empty.last() ?? -1); // -1last() follows the same absence and narrowing rules as first(), while reading the final element in O(1) without allocating a result array.
at()
Returns the element at an index, supporting negative indexing from the end.
at(index: i64): Tconst main = (): void => {
const colors: string[] = ["red", "green", "blue"];
const last: string? = colors.at(-1);
print(last ?? "none"); // blue
};error
const main = (): void => {
const colors: string[] = ["red", "green", "blue"];
const last: string? = colors.at("x");
};error[E0308]: type mismatch for `at`: expected `i64`, found `string`
at /src/main.tyr:3:27
const last: string? = colors.at("x"); // [!code error]
^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`keys()
Returns an iterator over the array indices.
keys(): Iterable<i64>const items: string[] = ["x", "y", "z"];
for (const index of items.keys()) {
print(index); // 0, 1, 2
}error
const items: string[] = ["x", "y", "z"];
const keys: i64[] = items.keys(); error[E0308]: type mismatch for `keys`: expected `i64[]`, found `usize[]`
at /src/main.tyr:2:7
const keys: i64[] = items.keys();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`values()
Returns an iterator over the array values.
values(): Iterable<T>const items: i32[] = [10, 20, 30];
let total: i32 = 0;
for (const value of items.values()) {
total += value;
}
print(total); // 60error
const items: i32[] = [10, 20, 30];
const vals: string[] = items.values(); error[E0308]: type mismatch for `vals`: expected `string[]`, found `i32[]`
at /src/main.tyr:2:7
const vals: string[] = items.values();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`entries()
Returns an iterator over index-value pairs.
entries(): Iterable<[i64, T]>const fruits: string[] = ["apple", "banana", "cherry"];
for (const [index, fruit] of fruits.entries()) {
print(`${index}: ${fruit}`);
// 0: apple
// 1: banana
// 2: cherry
}error
const fruits: string[] = ["apple", "banana", "cherry"];
const entries: [i64, string][] = fruits.entries(); error[E0308]: type mismatch for `entries`: expected `[i64, string][]`, found `[usize, string][]`
at /src/main.tyr:2:7
const entries: [i64, string][] = fruits.entries();
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Immutable Copy
with()
Returns a new array with a single element replaced at a given index.
with(index: i64, value: T): T[]const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, "yellow");
// ["red", "yellow", "blue"]
// colors is unchangederror
const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, 42); error[E0308]: type mismatch for `with`: expected `string`, found `integer literal`
at /src/main.tyr:2:27
const updated: string[] = colors.with(1, 42);
^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Toggle
toggle()
Adds an element to the array if it is not present, and removes it if it is present, returning a new array and never mutating the receiver.
toggle(item: T): T[]toggle(item: T, key: string): T[]const values: i32[] = [1, 2, 3];
print(values.toggle(4)); // [1, 2, 3, 4]
print(values.toggle(2)); // [1, 3]
print(values); // [1, 2, 3]When a key field name is given, matching is done by that field instead of by the element as a whole. The field must exist on the element type.
interface Pet {
name: string;
age: i32;
}
const pets: Pet[] = [
{ name: "rex", age: 2 },
{ name: "mia", age: 5 },
];
const adopted: Pet[] = pets.toggle({ name: "rex", age: 99 }, "name");
print(adopted.length); // 1toggleAll()
Applies the same add-or-remove behavior to every element of the argument array, preserving order. Mutates nothing.
toggleAll(items: T[]): T[]const values: i32[] = [1, 2, 3];
print(values.toggleAll([2, 4])); // [1, 3, 4]Chaining
Functional methods chain into readable data pipelines:
interface Product {
name: string;
price: f64;
inStock: boolean;
}
const products: Product[] = [
{ name: "Keyboard", price: 79.99, inStock: true },
{ name: "Mouse", price: 29.99, inStock: false },
{ name: "Monitor", price: 349.99, inStock: true },
{ name: "Headset", price: 59.99, inStock: true },
];
const availableNames: string[] = products
.filter(product => product.inStock)
.map(product => product.name);
// ["Keyboard", "Monitor", "Headset"]
const totalRevenue: f64 = products
.filter(product => product.inStock)
.reduce((sum, product) => sum + product.price, 0.0);
// 489.97