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]

Ambas formas T[] y Array<T> son válidas. Las lecturas y escrituras indexadas realizan chequeos de límite en tiempo de ejecución. Los métodos mutantes requieren un receiver let. length informa la cantidad de elementos, mientras que capacity es una extensión de tyrus de solo lectura que expone el almacenamiento nativo reservado.

Literales de array y valores repetidos ​

El tipo [T; N] declara un array con exactamente N elementos. Inicialízalo con una lista que contenga exactamente N valores o con [valor; N] para repetir un valor. Los literales de array sin una anotación de tamaño fijo, como T[], siguen teniendo tamaño dinámico.

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 construidos por una secuencia de push ​

Un array local que empieza vacío y se llena con una secuencia directa de push se compila como el literal de array equivalente, lo que le permite vivir en el stack en vez del heap:

tyrus
function build(seed: i32): i32[] {
    let values: i32[] = [];
    values.push(seed);
    values.push(seed + 1);
    values.push(seed + 2);

    return values;
}

La reescritura es exacta, mismos elementos, mismo orden, mismo tamaño, y el array sigue creciendo después. Solo se aplica mientras nada haya podido observar el array en el medio: la secuencia se detiene en el primer statement que no es un push sobre ese array, un elemento que lee el array en construcción nunca se mueve delante de él, y un elemento con spread descalifica la secuencia porque aporta un número desconocido de elementos. Los tipos de elemento se limitan a los copiados por valor.

Nada de esto es visible en el comportamiento, solo en cuánto asigna el programa. Hacer crecer un array de otro modo asigna incluso en una build de release, ya que el crecimiento es una llamada dentro de la cual el optimizador no puede mirar.

Chequeos de límite que un bucle ya probó ​

Toda lectura y escritura indexada se chequea en tiempo de ejecución, excepto donde un bucle alrededor ya probó que el chequeo no puede fallar. En la forma de conteo de abajo el cuerpo solo se alcanza cuando i < values.length, y nada entre esa prueba y el acceso al elemento puede cambiar ninguno de los dos lados, así que la comparación que el acceso emitiría es la condición del bucle escrita una segunda vez:

tyrus
function sweep(values: i32[]): i32 {
    let sum = 0;
    
    for (let i: usize = 0; i < values.length; i += 1) {
        sum += values[i];
    }

    return sum;
}

La prueba es deliberadamente estrecha, porque equivocarse en ella quita lo único que hay entre un índice malo y una lectura fuera del buffer. Un bucle solo califica cuando el contador se declara en su propio init a partir de un literal no negativo, la condición es exactamente contador < array.length, la actualización solo aumenta el contador por una constante, el array es un local, un parámetro o un global const que nada puede hacer crecer y, dentro del cuerpo, el array nunca se usa para nada más que indexación y length, mientras el contador nunca se escribe. Cualquier otra cosa mantiene el chequeo: un push en el cuerpo, un índice distinto del contador, una redeclaración de cualquiera de los dos nombres o una mención a cualquiera de ellos desde dentro de una closure.

Un chequeo que se mantiene se comporta exactamente como siempre, nombrando el índice ofensor y el tamaño del array en stderr antes de terminar con status distinto de cero.

Chequeos de límite que una tabla fija ya probó ​

Un bucle no es lo único que puede resolver un índice. Cuando un binding se declara const a partir de un literal de array, su cantidad de elementos está escrita en el código, y un índice literal por debajo de esa cantidad está dentro del rango sin ningún bucle involucrado:

tyrus
readonly const PRIMES: i32[] = [2, 3, 5, 7, 11, 13, 17, 19];

function third(): i32 {
    return PRIMES[2];
}

El chequeo de PRIMES[2] se elimina, y un índice más allá del final es un error de compilación en vez de uno de ejecución, PRIMES[8] se rechaza con E0606, nombrando el rango válido. Lo que fija el tamaño es el const, no la anotación: el binding no puede reasignarse, y un método mutante sobre él se rechaza. readonly const es como se escribe normalmente una tabla fija, pero un literal de array const simple prueba lo mismo.

El binding también tiene que ser solo leído y nada más. Pasarlo a una función, capturarlo en una closure o llamar cualquier método sobre él termina la prueba y el chequeo permanece, la misma regla estrecha que sigue la forma de bucle, y por el mismo motivo.

Los métodos mutables requieren let

Un array const es profundamente inmutable. Llamar a push, sort, reverse o a cualquier otro método mutable en un array const produce un error de compilación.

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

Propiedades ​

MiembroTipoComportamiento
lengthusizeCantidad actual de elementos.
capacityusizeAlmacenamiento nativo reservado; es una extensión de Tyrus.

Métodos mutables ​

Estos métodos modifican el array y, por eso, requieren un binding let mutable. pop() y shift() devuelven T?, así que un array vacío produce ausencia.

MétodoFirmaComportamiento
pushpush(...items: T[]): usizeAñade valores al final y devuelve la nueva longitud.
poppop(): T?Elimina y devuelve el último valor, o ausencia.
unshiftunshift(...items: T[]): usizeAñade valores al inicio y devuelve la nueva longitud.
shiftshift(): T?Elimina y devuelve el primer valor, o ausencia.
splicesplice(start: i64, deleteCount?: i64, ...items: T[]): T[]Elimina, reemplaza o inserta valores y devuelve los valores eliminados.

sort, reverse, rotate, fill y copyWithin también modifican el receiver. Su comportamiento se explica en Métodos funcionales.

Métodos estáticos ​

MétodoFirmaComportamiento
Array.ofArray.of(...items: T[]): T[]Crea un array con sus argumentos.
Array.fromArray.from(items: T[]): T[]Copia un array en un array de tamaño dinámico.
Array.withCapacityArray.withCapacity(capacity: usize): T[]Crea un array vacío con capacidad reservada.
Array.isArrayArray.isArray(value: unknown): booleanComprueba si un valor es un array.

Métodos Funcionales ​

CategoríaMétodos
Iteración & Transformaciónmap(), filter(), partition(), reduce(), reduceRight(), forEach()
Ventanas y Matriceswindows(), scan(), cartesianProduct(), zip(), transpose()
Deduplicación y Agrupaciónunique(), uniqueBy(), groupBy()
Toggletoggle(), toggleAll()
Búsqueda & Testfind(), findLast(), findIndex(), findLastIndex(), some(), every(), includes(), equals(), indexOf(), lastIndexOf()
Flatten & Reordenaciónflat(), flatMap(), sort(), toSorted(), sortBy(), sortedBy(), reverse(), rotate(), toReversed(), random(), shuffle(), sample()
Corteslice(), splitAt()
Agregaciónsum(), product(), avg(), sumBy(), avgBy(), count(), concat(), join()
Mutaciónsplice(), fill(), copyWithin()
Acceso & Iteraciónfirst(), last(), at(), keys(), values(), entries()
Copia Inmutablewith()

Iteración & Transformación ​

Los métodos basados en predicados (filter, partition, some, every, find, findLast, findIndex, findLastIndex, uniqueBy y groupBy) aceptan una callback arrow explícita o una expresión implícita como value > 2; el tipo del elemento se infiere a partir del array receptor.

map() ​

Crea un nuevo array aplicando una transformación a cada elemento.

Firmamap<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() ​

Selecciona elementos que satisfacen un predicado.

Firmafilter(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() ​

Separa los elementos en dos arrays estables según un predicado. El primer array contiene los elementos que coinciden; el segundo contiene los demás. El receiver no se modifica.

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

Los arrays de objetos pueden usar directamente el nombre de un campo booleano, o un campo string seguido de uno o más valores coincidentes. Los nombres de los campos se verifican contra el tipo del elemento en tiempo de compilación.

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" }]

Un campo desconocido se rechaza en tiempo de compilación.

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

Para predicados más complejos, usa una arrow function explícita. Puede recibir el elemento, su índice y el array original:

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() evalúa el predicado una vez por elemento y conserva el orden original dentro de los dos arrays de salida. Al igual que count(), una expresión común con exactamente un identificador libre se trata como predicado implícito por elemento; una arrow function explícita sigue disponible para casos más complejos. Por seguridad de memoria, T debe ser Copy, string o un objeto cuyos campos son Copy o string.

reduce() ​

Acumula elementos en un único valor, de izquierda a derecha.

Firmareduce<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() ​

Acumula elementos en un único valor, de derecha a izquierda.

FirmareduceRight<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() ​

Ejecuta un callback para cada elemento. El valor de retorno se descarta.

FirmaforEach(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`

Búsqueda & Test ​

find() ​

Devuelve el primer elemento que coincide con un predicado, o ausencia si ninguno coincide.

Firmafind(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() ​

Devuelve el último elemento que coincide con un predicado, o ausencia si ninguno coincide.

FirmafindLast(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() ​

Devuelve el índice del primer elemento que coincide, o -1.

FirmafindIndex(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() ​

Devuelve el índice del último elemento que coincide, o -1.

FirmafindLastIndex(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() ​

Comprueba si al menos un elemento satisface una condición.

Firmasome(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() ​

Comprueba si todos los elementos satisfacen una condición.

Firmaevery(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() ​

Comprueba si un valor específico existe en el array.

Firmaincludes(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() ​

Compara dos arrays elemento a elemento: la misma longitud, los mismos elementos, en el mismo orden. === y !== no comparan arrays; el compilador informa E0369 y remite aquí.

Firmaequals(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() ​

Devuelve el primer índice de un valor, o -1 si no se encuentra.

FirmaindexOf(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() ​

Devuelve el último índice de un valor, o -1 si no se encuentra.

FirmalastIndexOf(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>`

Ventanas, Acumulación y Matrices ​

windows() ​

windows(size) devuelve copias superpuestas de size elementos consecutivos. El receiver no cambia; windows(0) se rechaza y un tamaño mayor que el array devuelve un array vacío.

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) devuelve el acumulador inicial seguido por cada valor acumulado. La callback recibe el acumulador y el elemento actual, y el receiver no cambia.

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) devuelve pares en orden lexicográfico del receiver y del argumento. Cualquier entrada vacía produce un resultado vacío, y el receiver no cambia.

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) intercala el receiver y el argumento en un array de pares (T, U)[], donde T es el tipo de elemento del receiver y U es el tipo de elemento del argumento. La longitud del resultado es igual a la de ambas entradas, que deben coincidir; los arrays de origen no cambian.

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);
}

Una diferencia de longitud lanza un ZipError recuperable (code ERR_ARRAY_ZIP_MISMATCH) en lugar de abortar, por lo que la llamada debe cubrirse con un catch o con una cláusula throws ZipError en la función que la contiene:

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() convierte una matriz rectangular en columnas. Las matrices vacías y las matrices con filas de ancho cero devuelven arrays vacíos; las filas irregulares fallan antes de producir un resultado parcial.

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() devuelve la primera aparición de cada valor distinto en el orden de entrada. No muta el receiver y usa la política nativa de igualdad para strings y números.

tyrus
const values: i32[] = [3, 1, 3, 2, 1];
const distinct: i32[] = values.unique(); // [3, 1, 2]
print(distinct);

uniqueBy() ​

uniqueBy(selector) conserva el primer elemento para cada clave hashable distinta. El selector puede ser el nombre de un campo para elementos objeto, una callback explícita o una expresión implícita, cuyo tipo de elemento se infiere automáticamente.

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) crea un mapa desde cada clave hashable hacia un array de elementos en su orden original. El selector puede ser el nombre de un campo para elementos objeto, una callback explícita o una expresión implícita, cuyo tipo de elemento se infiere automáticamente. La primera implementación exige elementos Copy para que cada grupo sea propietario de sus valores de forma segura.

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 & Reordenación ​

flat() ​

Aplana arrays anidados en un nivel.

Firmaflat(): 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() ​

Mapea cada elemento a un array y aplana el resultado en un nivel.

FirmaflatMap<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() ​

Ordena el array in place usando una función de comparación.

Firmasort(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() ​

Devuelve una nueva copia ordenada sin mutar el original.

FirmatoSorted(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() ​

Ordena un array in place por un campo resuelto estáticamente. La clave debe ser un literal string con el nombre de un campo numérico, booleano, de carácter o string. El segundo argumento es opcional: el orden predeterminado es ascendente y "desc" selecciona el orden descendente.

FirmasortBy(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 }]

El campo se resuelve en compile-time, por lo que el bucle de merge sort estable generado lo lee directamente sin reflexión en runtime. sortBy() requiere un receiver mutable en let y funciona en O(n log n) con O(n) de espacio auxiliar.

sortedBy() ​

Devuelve una copia ordenada por un campo resuelto estáticamente y deja el receiver sin cambios. El segundo argumento es opcional: el orden predeterminado es ascendente y "desc" selecciona el orden descendente. La primera versión requiere que los campos del elemento sean Copy, evitando una copia superficial insegura de valores poseídos. Usa merge sort estable O(n log n) con O(n) de espacio auxiliar.

FirmasortedBy(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() ​

Invierte el orden de los elementos in place.

Firmareverse(): 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() ​

Rota el array in place. Los valores positivos rotan hacia la izquierda; los negativos rotan hacia la derecha. El valor se normaliza por la longitud del array, y los arrays vacíos o de un solo elemento no cambian.

Firmarotate(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() requiere un receiver mutable en let y se ejecuta en O(n) con espacio auxiliar O(1), sin asignar un segundo array.

toReversed() ​

Devuelve una nueva copia con orden invertido sin mutar el original.

FirmatoReversed(): 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() ​

Devuelve un T seleccionado uniformemente. Un array vacío aborta en runtime.

Firmarandom(): 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() ​

Devuelve un nuevo array mezclado uniformemente sin mutar el receptor. Los arrays con menos de dos elementos abortan en runtime.

Firmashuffle(): 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() ​

Devuelve un nuevo array con count elementos seleccionados uniformemente. count debe estar entre 1 y la longitud del receptor, inclusive. Sin opciones, las posiciones de origen no se repiten. { repeat: true } permite repeticiones de posiciones, pero no las garantiza.

Firmasample(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);
                             ^

Corte ​

slice() ​

Extrae una copia de un subarray contiguo.

Firmaslice(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>`

Indexar con un Range es azúcar para .slice(): arr[a..b] es arr.slice(a, b), y toda forma abierta también funciona, arr[a..], arr[..b], arr[..=b] y el rango completo arr[..]. Igual que .slice(), esto siempre copia a un array nuevo; los arrays de tyrus todavía no tienen representación de slice prestado sin copia.

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() ​

Divide el array en dos arrays en un índice dado.

FirmasplitAt(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 siempre devuelve dos arrays comunes de tamaño dinámico ([T[], T[]]), incluso cuando se llama sobre un array de tamaño fijo. index puede ser igual a la longitud del array, produciendo una segunda mitad vacía, pero un índice mayor es un error de compilación cuando la longitud del array se conoce estáticamente, y un abort en tiempo de ejecución en caso contrario.

Agregación ​

count() ​

Devuelve la longitud, o cuenta ocurrencias de un valor o predicado.

Firmacount(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() devuelve la longitud; count(valor) cuenta elementos iguales a valor; count(condición), una expresión común que referencia exactamente un identificador todavía no declarado en el ámbito actual, se convierte en una condición implícita por elemento, azúcar para count((implicitParam): boolean => condición) sin necesidad de escribir ninguna arrow function. Un identificador que ya resuelve en el ámbito no es libre, así que la expresión se comprueba como una llamada común count(valor), comparar su resultado (constante) boolean contra el tipo del elemento es un error de compilación que cita el identificador que ensombreció el parámetro implícito. Una expresión que referencia más de un identificador no declarado también es un error de compilación, ya que el azúcar solo introduce un parámetro implícito.

sum() ​

Devuelve la suma de todos los elementos numéricos usando el tipo de los elementos del array. Un array numérico vacío devuelve el valor cero de ese tipo.

Firmasum(): 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() se rechaza para tipos de elemento no numéricos y se compila como un bucle nativo directo, sin callback ni despacho al runtime por elemento.

product() ​

Devuelve el producto de todos los elementos numéricos usando el tipo de los elementos del array. Un array numérico vacío devuelve el valor uno de ese tipo.

Firmaproduct(): 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() sigue las mismas reglas de tipo numérico y bucle nativo que sum().

avg() ​

Devuelve el promedio aritmético de los elementos numéricos. Los arrays de enteros, f32 y f64 devuelven f64?; los arrays de f128 devuelven f128?. Un array vacío produce ausencia.

Firmaavg(): 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

El resultado opcional debe tratarse con ??, narrowing u otra operación válida de opcionales antes del uso numérico directo.

sumBy() ​

Retorna la suma de un campo numérico en todos los elementos. La clave debe ser un literal de string que nombre un campo numérico.

FirmasumBy(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() ​

Retorna el promedio aritmético de un campo numérico en todos los elementos. La clave debe ser un literal de string que nombre un campo numérico. Siempre retorna f64? (o f128? para campos f128).

FirmaavgBy(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() ​

Fusiona dos arrays en uno nuevo.

Firmaconcat(...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() ​

Une todos los elementos en una sola cadena usando un separador.

Firmajoin(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(", ");
                     ^^^^^^^^^^^^^^^^^^

Mutación ​

splice() ​

Elimina, reemplaza o inserta elementos in place.

Firmasplice(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) modifica el receptor y devuelve un nuevo array con los elementos eliminados. Los índices iniciales negativos cuentan desde el final, la eliminación se limita al intervalo disponible y los valores insertados deben coincidir con el tipo de los elementos del array.

fill() ​

Reemplaza todos los elementos con un valor fijo.

Firmafill(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() ​

Copia una sección contigua del array a otra posición en el mismo array.

FirmacopyWithin(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>`

Acceso & Iteración ​

first() ​

Devuelve el primer elemento como T?. Un array vacío produce ausencia. La anotación de tipo es opcional: cuando values es i32[], tyrus infiere i32? automáticamente. Optional<i32> es la forma explícita equivalente.

Firmafirst(): 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? es intencional: first() devuelve un valor, no una colección, y sigue siendo O(1) sin asignar un array vacío como resultado. El uso directo como i32 se rechaza hasta que un if, ??, ternario, optional chaining u otra operación válida de narrowing trate la ausencia.

last() ​

Devuelve el último elemento como T?. Un array vacío produce ausencia, y tyrus infiere automáticamente el tipo opcional del elemento cuando se omite la anotación.

Firmalast(): 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() sigue las mismas reglas de ausencia y narrowing que first(), leyendo el elemento final en O(1) sin asignar un array de resultado.

at() ​

Devuelve el elemento en un índice, soportando indexación negativa desde el final.

Firmaat(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() ​

Devuelve un iterador sobre los índices del array.

Firmakeys(): 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() ​

Devuelve un iterador sobre los valores del array.

Firmavalues(): 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() ​

Devuelve un iterador sobre pares índice-valor.

Firmaentries(): 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>`

Copia Inmutable ​

with() ​

Devuelve un nuevo array con un único elemento reemplazado en un índice dado.

Firmawith(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() ​

Agrega un elemento al array si no está presente y lo elimina si está presente, devolviendo un array nuevo y sin mutar nunca el receptor.

Firmatoggle(item: T): T[]
Firmatoggle(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]

Cuando se proporciona un nombre de campo key, la comparación se hace por ese campo en lugar de por el elemento completo. El campo debe existir en el tipo del elemento.

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() ​

Aplica el mismo comportamiento de agregar o eliminar a cada elemento del array argumento, preservando el orden. No muta nada.

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

Encadenamiento ​

Los métodos funcionales se encadenan en pipelines de datos legibles:

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