Skip to content

Arrays ​

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

tyrus
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

tyrus
const most: [u8; 3] = [10, 20, 30, 40]; 
text
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 initializer

Arrays 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:

tyrus
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:

tyrus
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:

tyrus
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

tyrus
const fixed: i32[] = [1, 2, 3];

fixed.push(4); 
text
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 assignment

Properties ​

MemberTypeBehavior
lengthusizeCurrent number of elements.
capacityusizeReserved 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.

MethodSignatureBehavior
pushpush(...items: T[]): usizeAppends values and returns the new length.
poppop(): T?Removes and returns the last value, or absence.
unshiftunshift(...items: T[]): usizePrepends values and returns the new length.
shiftshift(): T?Removes and returns the first value, or absence.
splicesplice(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 ​

MethodSignatureBehavior
Array.ofArray.of(...items: T[]): T[]Creates an array from its arguments.
Array.fromArray.from(items: T[]): T[]Copies an array into a dynamically sized array.
Array.withCapacityArray.withCapacity(capacity: usize): T[]Creates an empty array with reserved capacity.
Array.isArrayArray.isArray(value: unknown): booleanChecks whether a value is an array.

Functional Methods ​

CategoryMethods
Iteration & Transformationmap(), filter(), partition(), reduce(), reduceRight(), forEach()
Windowing & Matriceswindows(), scan(), cartesianProduct(), zip(), transpose()
Deduplication & Groupingunique(), uniqueBy(), groupBy()
Toggletoggle(), toggleAll()
Search & Testfind(), findLast(), findIndex(), findLastIndex(), some(), every(), includes(), equals(), indexOf(), lastIndexOf()
Flatten & Reorderflat(), flatMap(), sort(), toSorted(), sortby(), sortedby(), reverse(), rotate(), toReversed(), random(), shuffle(), sample()
Slicingslice(), splitAt()
Aggregationsum(), product(), avg(), sumBy(), avgBy(), count(), concat(), join()
Mutationsplice(), fill(), copyWithin()
Access & Iterationfirst(), last(), at(), keys(), values(), entries()
Immutable Copywith()

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.

Signaturemap<U>(callback: (element: T, index?: i64) => U): U[]
tyrus
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

tyrus
const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: string[] = prices.map(price => price * 1.08); 
text
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.

Signaturefilter(predicate: (element: T) => boolean): T[]
tyrus
const scores: i32[] = [85, 42, 91, 38, 76, 55];
const passing: i32[] = scores.filter(score => score >= 60);
// [85, 91, 76]

error

tyrus
const scores: i32[] = [85, 42, 91, 38, 76, 55];
const result: i32[] = scores.filter(score => score * 2); 
text
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.

Signaturepartition(predicate: (element: T) => boolean): [T[], T[]]
Signaturepartition(field: string): [T[], T[]]
Signaturepartition(field: string, ...values: string[]): [T[], T[]]
tyrus
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.

tyrus
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

tyrus
interface Ticket {
    completed: boolean;
}

const tickets: Ticket[] = [{ completed: true }];
const [completed, pending] = tickets.partition("archived"); 
text
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 type

For more complex predicates, use an explicit arrow function. It can receive the element, its index, and the original array:

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

Signaturereduce<U>(callback: (accumulator: U, element: T) => U, initial: U): U
tyrus
const values: i32[] = [10, 20, 30, 40];
const total: i32 = values.reduce((sum, value) => sum + value, 0);
// 100

error

tyrus
const values: i32[] = [10, 20, 30, 40];
const total: i64 = values.reduce((sum, value) => sum + value, 0); 
text
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.

SignaturereduceRight<U>(callback: (accumulator: U, element: T) => U, initial: U): U
tyrus
const letters: string[] = ["a", "b", "c", "d"];
const reversed: string = letters.reduceRight(
  (acc, letter) => acc + letter, "",
);
// "dcba"

error

tyrus
const letters: string[] = ["a", "b", "c", "d"];
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, ""); 
text
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.

SignatureforEach(callback: (element: T) => void): void
tyrus
const colors: string[] = ["red", "green", "blue"];
colors.forEach(color => print(color));
// red
// green
// blue

error

tyrus
const colors: string[] = ["red", "green", "blue"];
colors.forEach((color: i32) => print(color)); 
text
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.

Signaturefind(predicate: (element: T) => boolean): T?
tyrus
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string? = users.find(name => name.startsWith("G"));
// "Grace"

error

tyrus
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string = users.find(name => name.startsWith("G")); 
text
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 keyword

findLast() ​

Returns the last element matching a predicate, or absence if none match.

SignaturefindLast(predicate: (element: T) => boolean): T?
tyrus
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string? = users.findLast(name => name.startsWith("G"));
// "Gordon"

error

tyrus
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string = users.findLast(name => name.startsWith("G")); 
text
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.

SignaturefindIndex(predicate: (element: T) => boolean): i64
tyrus
const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item === "banana");
// 1

error

tyrus
const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item.length); 
text
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.

SignaturefindLastIndex(predicate: (element: T) => boolean): i64
tyrus
const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n === 2);
// 3

error

tyrus
const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n); 
text
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.

Signaturesome(predicate: (element: T) => boolean): boolean
tyrus
const ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age < 18);
// true

error

tyrus
const ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age * 2); 
text
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.

Signatureevery(predicate: (element: T) => boolean): boolean
tyrus
const temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t >= 36.0 && t <= 37.5);
// true

error

tyrus
const temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t + 1); 
text
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.

Signatureincludes(value: T): boolean
tyrus
const fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes("banana");
// true

error

tyrus
const fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes(42); 
text
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.

Signatureequals(other: T[]): boolean
tyrus
const 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]);
// false

error

tyrus
const grid: i32[][] = [[1], [2]];
const same: boolean = grid.equals([[1], [2]]); 
text
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.

SignatureindexOf(value: T, fromIndex?: i64): i64
tyrus
const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf(2);
// 1

error

tyrus
const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf("2"); 
text
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.

SignaturelastIndexOf(value: T, fromIndex?: i64): i64
tyrus
const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf(2);
// 3

error

tyrus
const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf("2"); 
text
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.

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

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

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

tyrus
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:

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

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

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

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

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

Signatureflat(): T[]
tyrus
const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: i32[] = matrix.flat();
// [1, 2, 3, 4, 5]

error

tyrus
const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: string[] = matrix.flat(); 
text
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.

SignatureflatMap<U>(callback: (element: T) => U[]): U[]
tyrus
const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence.split(" "));
// ["hello", "world", "goodbye", "moon"]

error

tyrus
const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence); 
text
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.

Signaturesort(compare?: (left: T, right: T) => i32): this
tyrus
let numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left - right);
// [4, 8, 15, 23, 42]

error

tyrus
let numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left < right); 
text
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.

SignaturetoSorted(compare?: (left: T, right: T) => i32): T[]
tyrus
const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left - right);
// [4, 8, 15, 23, 42]
// original is unchanged

error

tyrus
const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left > right); 
text
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.

SignaturesortBy(key: keyof T, order?: "asc" | "desc"): this
tyrus
interface 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.

SignaturesortedBy(key: keyof T, order?: "asc" | "desc"): T[]
tyrus
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.

Signaturereverse(): this
tyrus
let stack: i32[] = [1, 2, 3];
stack.reverse();
// [3, 2, 1]

error

tyrus
const stack: i32[] = [1, 2, 3];
stack.reverse(); 
text
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 assignment

rotate() ​

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.

Signaturerotate(amount: i64): this
tyrus
let 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.

SignaturetoReversed(): T[]
tyrus
const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: string[] = days.toReversed();
// ["Wed", "Tue", "Mon"]
// days is unchanged

error

tyrus
const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: i32[] = days.toReversed(); 
text
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.

Signaturerandom(): T
tyrus
const fruits = ["grape", "banana", "orange", "strawberry"];
const chosen = fruits.random();
print(chosen); // "orange"

error

tyrus
const fruits: string[] = [];
const chosen = fruits.random(); 
text
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.

Signatureshuffle(): T[]
tyrus
const fruits = ["grape", "banana", "orange", "strawberry"];
const shuffled = fruits.shuffle();
print(shuffled); // ["banana", "strawberry", "grape", "orange"]

error

tyrus
const value = [1];
const shuffled = value.shuffle(); 
text
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.

Signaturesample(count: usize, options?: { repeat?: boolean }): T[]
tyrus
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

tyrus
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const none = teams.sample(0); 
text
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

tyrus
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const tooMany = teams.sample(4); 
text
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.

Signatureslice(start?: i64, end?: i64): T[]
tyrus
const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: string[] = letters.slice(1, 4);
// ["b", "c", "d"]

error

tyrus
const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: i32[] = letters.slice(1, 4); 
text
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.

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

SignaturesplitAt(index: i64): [T[], T[]]
tyrus
const letters: string[] = ["a", "b", "c", "d", "e"];
const parts: [string[], string[]] = letters.splitAt(2);
// [["a", "b"], ["c", "d", "e"]]

error

tyrus
const letters: string[] = ["a", "b"];
const parts: [string[], string[]] = letters.splitAt(10); 
text
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.

Signaturecount(value?: T | (element: T) => boolean): i64
tyrus
const 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));       // 3

error

tyrus
const numbers: i32[] = [1, 2, 3, 4, 5, 6];
const total: i64 = numbers.count(value => value.toString()); 
text
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.

Signaturesum(): T
tyrus
const values: i32[] = [2, 3, 4];
const total = values.sum(); // inferred as i32
print(total); // 9

const empty: i32[] = [];
print(empty.sum()); // 0

sum() 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.

Signatureproduct(): T
tyrus
const values: i32[] = [2, 3, 4];
const product = values.product(); // inferred as i32
print(product); // 24

const empty: i32[] = [];
print(empty.product()); // 1

product() 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.

Signatureavg(): f64? | f128?
tyrus
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.0

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

SignaturesumBy(key: string): T[K]
tyrus
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).

SignatureavgBy(key: string): f64? | f128?
tyrus
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.

Signatureconcat(...items: (T | T[])[]): T[]
tyrus
const front: i32[] = [1, 2];
const back: i32[] = [3, 4];
const merged: i32[] = front.concat(back);
// [1, 2, 3, 4]

error

tyrus
const front: string[] = ["a", "b"];
const merged: string[] = front.concat(42); 
text
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.

Signaturejoin(separator: string): string
tyrus
const parts: string[] = ["tyrus", "is", "native"];
const sentence: string = parts.join(" ");
// "tyrus is native"

error

tyrus
const numbers: i32[] = [1, 2, 3];
const text: string = numbers.join(", "); 
text
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.

Signaturesplice(start: i64, deleteCount?: i64, ...items: T[]): T[]
tyrus
let values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8);
print(values[1]);
print(removed[0]);

error

tyrus
const values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8); 
text
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 assignment

splice(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.

Signaturefill(value: T): this
tyrus
let buffer: i32[] = [0, 0, 0, 0, 0];

buffer.fill(7);
// [7, 7, 7, 7, 7]

error

tyrus
let buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill("x"); 
text
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.

SignaturecopyWithin(target: i64, start: i64, end?: i64): this
tyrus
let data: i32[] = [1, 2, 3, 4, 5];

data.copyWithin(0, 3);
// [4, 5, 3, 4, 5]

error

tyrus
let data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin("x", 3); 
text
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.

Signaturefirst(): T?
tyrus
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); // -1

T? 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.

Signaturelast(): T?
tyrus
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); // -1

last() 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.

Signatureat(index: i64): T
tyrus
const main = (): void => {
    const colors: string[] = ["red", "green", "blue"];
    const last: string? = colors.at(-1);
    print(last ?? "none"); // blue
};

error

tyrus
const main = (): void => {
    const colors: string[] = ["red", "green", "blue"];
    const last: string? = colors.at("x"); 
};
text
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.

Signaturekeys(): Iterable<i64>
tyrus
const items: string[] = ["x", "y", "z"];
for (const index of items.keys()) {
    print(index); // 0, 1, 2
}

error

tyrus
const items: string[] = ["x", "y", "z"];
const keys: i64[] = items.keys(); 
text
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.

Signaturevalues(): Iterable<T>
tyrus
const items: i32[] = [10, 20, 30];
let total: i32 = 0;
for (const value of items.values()) {
    total += value;
}
print(total); // 60

error

tyrus
const items: i32[] = [10, 20, 30];
const vals: string[] = items.values(); 
text
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.

Signatureentries(): Iterable<[i64, T]>
tyrus
const fruits: string[] = ["apple", "banana", "cherry"];

for (const [index, fruit] of fruits.entries()) {
    print(`${index}: ${fruit}`);
    // 0: apple
    // 1: banana
    // 2: cherry
}

error

tyrus
const fruits: string[] = ["apple", "banana", "cherry"];
const entries: [i64, string][] = fruits.entries(); 
text
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.

Signaturewith(index: i64, value: T): T[]
tyrus
const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, "yellow");
// ["red", "yellow", "blue"]
// colors is unchanged

error

tyrus
const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, 42); 
text
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.

Signaturetoggle(item: T): T[]
Signaturetoggle(item: T, key: string): T[]
tyrus
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.

tyrus
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); // 1

toggleAll() ​

Applies the same add-or-remove behavior to every element of the argument array, preserving order. Mutates nothing.

SignaturetoggleAll(items: T[]): T[]
tyrus
const values: i32[] = [1, 2, 3];
print(values.toggleAll([2, 4])); // [1, 3, 4]

Chaining ​

Functional methods chain into readable data pipelines:

tyrus
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