Arrays
const names: string[] = ["Ada", "Linus"];
const first: string = names[0]; // "Ada"
const count: usize = names.length; // 2
let statuses: Array<i32> = [200, 201];
statuses[1] = 204; // [200, 204]
statuses.push(202); // [200, 204, 202]
const successful: boolean = statuses.includes(200); // true
const page: i32[] = statuses.slice(0, 2); // [200, 204]
const immutableReverse: i32[] = statuses.toReversed(); // [202, 204, 200]Ambas as formas T[] e Array<T> são aceitas. Leituras e escritas indexadas realizam checagens de limite em tempo de execução. Métodos mutantes exigem um receiver let. length informa a quantidade de elementos, enquanto capacity é uma extensão do tyrus somente leitura que expõe o armazenamento nativo reservado.
Literais de array e valores repetidos
O tipo [T; N] declara um array com exatamente N elementos. Inicialize-o com uma lista contendo exatamente N valores ou com [valor; N] para repetir um valor. Literais de array sem anotação de tamanho fixo, como T[], continuam tendo tamanho dinâmico.
const repeated: [i32; 5] = [0; 5];
const values: [i32; 5] = [1, 2, 3, 4, 5];
print(repeated); // [0, 0, 0, 0, 0]
print(values); // [1, 2, 3, 4, 5]error
const most: [u8; 3] = [10, 20, 30, 40]; error[E0308]: fixed-length type requires 3 elements, but this initializer contains 4
at /src/main.tyr:1:23
const most: [u8; 3] = [10, 20, 30, 40];
^^^^^^^^^^^^^^^^
help: provide exactly 3 elements in this initializerArrays construídos por uma sequência de push
Um array local que começa vazio e é preenchido por uma sequência direta de push é compilado como o literal de array equivalente, o que permite que ele viva na pilha em vez do heap:
function build(seed: i32): i32[] {
let values: i32[] = [];
values.push(seed);
values.push(seed + 1);
values.push(seed + 2);
return values;
}A reescrita é exata, mesmos elementos, mesma ordem, mesmo tamanho, e o array continua crescendo depois. Ela só se aplica enquanto nada puder ter observado o array no meio: a sequência para no primeiro statement que não é um push naquele array, um elemento que lê o array em construção nunca é movido para antes dele, e um elemento com spread desqualifica a sequência por contribuir com um número desconhecido de elementos. Os tipos de elemento se limitam aos copiados por valor.
Nada disso é visível no comportamento, apenas em quanto o programa aloca. Crescer um array de outro modo aloca até em build de release, já que o crescimento é uma chamada dentro da qual o otimizador não consegue olhar.
Checagens de limite que um laço já provou
Toda leitura e escrita indexada é checada em tempo de execução, exceto onde um laço em volta já provou que a checagem não pode falhar. No formato de contagem abaixo o corpo só é alcançado quando i < values.length, e nada entre esse teste e o acesso ao elemento pode mudar qualquer um dos dois lados, então a comparação que o acesso emitiria é a condição do laço escrita uma segunda vez:
function sweep(values: i32[]): i32 {
let sum = 0;
for (let i: usize = 0; i < values.length; i += 1) {
sum += values[i];
}
return sum;
}A prova é deliberadamente estreita, porque errar nela remove a única coisa entre um índice ruim e uma leitura fora do buffer. Um laço só se qualifica quando o contador é declarado pelo init dele mesmo a partir de um literal não negativo, a condição é exatamente contador < array.length, a atualização apenas aumenta o contador por uma constante, o array é um local, um parâmetro ou um global const que nada pode fazer crescer e, dentro do corpo, o array nunca é usado para nada além de indexação e length, enquanto o contador nunca é escrito. Qualquer outra coisa mantém a checagem: um push no corpo, um índice diferente do contador, uma redeclaração de qualquer um dos dois nomes ou uma menção a qualquer um deles de dentro de uma closure.
Uma checagem mantida se comporta exatamente como sempre se comportou, nomeando o índice ofensor e o tamanho do array em stderr antes de encerrar com status diferente de zero.
Checagens de limite que uma tabela fixa já provou
Um laço não é a única coisa que pode resolver um índice. Quando um binding é declarado const a partir de um literal de array, a contagem de elementos dele está escrita no código, e um índice literal abaixo dessa contagem está dentro do intervalo sem laço nenhum envolvido:
readonly const PRIMES: i32[] = [2, 3, 5, 7, 11, 13, 17, 19];
function third(): i32 {
return PRIMES[2];
}A checagem de PRIMES[2] é removida, e um índice além do fim é erro de compilação em vez de erro de execução, PRIMES[8] é rejeitado com E0606, nomeando o intervalo válido. O que fixa o tamanho é o const, não a anotação: o binding não pode ser reatribuído, e um método mutante sobre ele é rejeitado. readonly const é como uma tabela fixa normalmente se escreve, mas um literal de array const simples prova a mesma coisa.
O binding também precisa ser apenas lido e nada mais. Passá-lo para uma função, capturá-lo numa closure ou chamar qualquer método sobre ele encerra a prova e a checagem permanece, a mesma regra estreita que o formato de laço segue, e pelo mesmo motivo.
Métodos mutáveis exigem let
Um array const é profundamente imutável. Chamar push, sort, reverse ou outro método mutável em um array const gera um erro de compilação.
error
const fixed: i32[] = [1, 2, 3];
fixed.push(4); error[E0384]: cannot call mutating method `push` on immutable array `fixed`
at /src/main.tyr:3:1
fixed.push(4);
^^^^^
help: declare the binding with `let` to allow assignmentPropriedades
| Membro | Tipo | Comportamento |
|---|---|---|
length | usize | Quantidade atual de elementos. |
capacity | usize | Armazenamento nativo reservado; esta é uma extensão do Tyrus. |
Métodos mutáveis
Esses métodos alteram o array e, por isso, exigem um binding let mutável. pop() e shift() retornam T?, então um array vazio produz ausência.
| Método | Assinatura | Comportamento |
|---|---|---|
push | push(...items: T[]): usize | Adiciona valores ao final e retorna o novo tamanho. |
pop | pop(): T? | Remove e retorna o último valor, ou ausência. |
unshift | unshift(...items: T[]): usize | Adiciona valores no início e retorna o novo tamanho. |
shift | shift(): T? | Remove e retorna o primeiro valor, ou ausência. |
splice | splice(start: i64, deleteCount?: i64, ...items: T[]): T[] | Remove, substitui ou insere valores e retorna os valores removidos. |
sort, reverse, rotate, fill e copyWithin também alteram o receiver. O comportamento deles está em Métodos funcionais.
Métodos estáticos
| Método | Assinatura | Comportamento |
|---|---|---|
Array.of | Array.of(...items: T[]): T[] | Cria um array com os argumentos recebidos. |
Array.from | Array.from(items: T[]): T[] | Copia um array para um array de tamanho dinâmico. |
Array.withCapacity | Array.withCapacity(capacity: usize): T[] | Cria um array vazio com capacidade reservada. |
Array.isArray | Array.isArray(value: unknown): boolean | Verifica se um valor é um array. |
Métodos Funcionais
| Categoria | Métodos |
|---|---|
| Iteração & Transformação | map(), filter(), partition(), reduce(), reduceRight(), forEach() |
| Janelas e Matrizes | windows(), scan(), cartesianProduct(), zip(), transpose() |
| Deduplicação e Agrupamento | unique(), uniqueBy(), groupBy() |
| Toggle | toggle(), toggleAll() |
| Busca & Teste | find(), findLast(), findIndex(), findLastIndex(), some(), every(), includes(), equals(), indexOf(), lastIndexOf() |
| Flatten & Reordenação | flat(), flatMap(), sort(), toSorted(), sortBy(), sortedBy(), reverse(), rotate(), toReversed(), random(), shuffle(), sample() |
| Fatiamento | slice(), splitAt() |
| Agregação | sum(), product(), avg(), sumBy(), avgBy(), count(), concat(), join() |
| Mutação | splice(), fill(), copyWithin() |
| Acesso & Iteração | first(), last(), at(), keys(), values(), entries() |
| Cópia Imutável | with() |
Iteração & Transformação
Os métodos baseados em predicado (filter, partition, some, every, find, findLast, findIndex, findLastIndex, uniqueBy e groupBy) aceitam uma callback arrow explícita ou uma expressão implícita como value > 2; o tipo do elemento é inferido a partir do array receptor.
map()
Cria um novo array aplicando uma transformação a cada elemento.
map<U>(callback: (element: T, index?: i64) => U): U[]const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: f64[] = prices.map(price => price * 1.08);
// [10.7892, 21.5892, 32.3892]error
const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: string[] = prices.map(price => price * 1.08); error[E0308]: type mismatch for `withTax`: expected `string[]`, found `f64[]`
at /src/main.tyr:2:7
const withTax: string[] = prices.map(price => price * 1.08);
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`filter()
Seleciona elementos que satisfazem um predicado.
filter(predicate: (element: T) => boolean): T[]const scores: i32[] = [85, 42, 91, 38, 76, 55];
const passing: i32[] = scores.filter(score => score >= 60);
// [85, 91, 76]error
const scores: i32[] = [85, 42, 91, 38, 76, 55];
const result: i32[] = scores.filter(score => score * 2); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:46
const result: i32[] = scores.filter(score => score * 2);
^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`partition()
Separa os elementos em dois arrays estáveis de acordo com um predicado. O primeiro array contém os elementos que correspondem; o segundo contém os demais. O receiver não é alterado.
partition(predicate: (element: T) => boolean): [T[], T[]]partition(field: string): [T[], T[]]partition(field: string, ...values: string[]): [T[], T[]]const values: i32[] = [1, 2, 3, 4];
const [evenValues, oddValues] = values.partition(value % 2 === 0);
print(evenValues); // [2, 4]
print(oddValues); // [1, 3]
print(values); // [1, 2, 3, 4]Arrays de objetos podem usar diretamente o nome de um campo booleano, ou um campo string seguido de um ou mais valores correspondentes. Os nomes dos campos são verificados contra o tipo do elemento em tempo de compilação.
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" }]Um campo desconhecido é rejeitado em tempo de compilação.
error
interface Ticket {
completed: boolean;
}
const tickets: Ticket[] = [{ completed: true }];
const [completed, pending] = tickets.partition("archived"); error[E0609]: `partition` key `archived` is not a field of `Ticket`
at /src/main.tyr:6:30
const [completed, pending] = tickets.partition("archived");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typePara predicados mais complexos, use uma arrow function explícita. Ela pode receber o elemento, seu índice e o array original:
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() avalia o predicado uma vez por elemento e preserva a ordem original dentro dos dois arrays de saída. Assim como em count(), uma expressão comum com exatamente um identificador livre é tratada como predicado implícito por elemento; uma arrow function explícita continua disponível para casos mais complexos. Por segurança de memória, T precisa ser Copy, string ou um objeto cujos campos são Copy ou string.
reduce()
Acumula elementos em um único valor, da esquerda para a direita.
reduce<U>(callback: (accumulator: U, element: T) => U, initial: U): Uconst values: i32[] = [10, 20, 30, 40];
const total: i32 = values.reduce((sum, value) => sum + value, 0);
// 100error
const values: i32[] = [10, 20, 30, 40];
const total: i64 = values.reduce((sum, value) => sum + value, 0); error[E0308]: type mismatch for `total`: expected `i64`, found `i32`
at /src/main.tyr:2:7
const total: i64 = values.reduce((sum, value) => sum + value, 0);
^^^^^
help: `i32` does not convert to `i64` on its own; write the conversion explicitly with `as i64`reduceRight()
Acumula elementos em um único valor, da direita para a esquerda.
reduceRight<U>(callback: (accumulator: U, element: T) => U, initial: U): Uconst letters: string[] = ["a", "b", "c", "d"];
const reversed: string = letters.reduceRight(
(acc, letter) => acc + letter, "",
);
// "dcba"error
const letters: string[] = ["a", "b", "c", "d"];
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, ""); error[E0308]: type mismatch for `reversed`: expected `i64`, found `string`
at /src/main.tyr:2:7
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, "");
^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`forEach()
Executa um callback para cada elemento. O valor de retorno é descartado.
forEach(callback: (element: T) => void): voidconst colors: string[] = ["red", "green", "blue"];
colors.forEach(color => print(color));
// red
// green
// blueerror
const colors: string[] = ["red", "green", "blue"];
colors.forEach((color: i32) => print(color)); error[E0308]: type mismatch for callback parameter `color` of `forEach`: expected `string`, found `i32`
at /src/main.tyr:2:24
colors.forEach((color: i32) => print(color));
^^^
help: change the callback parameter type to `string`Busca & Teste
find()
Retorna o primeiro elemento que satisfaz um predicado, ou ausência se nenhum satisfizer.
find(predicate: (element: T) => boolean): T?const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string? = users.find(name => name.startsWith("G"));
// "Grace"error
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string = users.find(name => name.startsWith("G")); error[E0003]: `match` is a reserved keyword in tyrus and cannot be used as an identifier
at /src/main.tyr:2:7
const match: string = users.find(name => name.startsWith("G"));
^^^^^
help: rename `match` to an identifier that is not a reserved keywordfindLast()
Retorna o último elemento que satisfaz um predicado, ou ausência se nenhum satisfizer.
findLast(predicate: (element: T) => boolean): T?const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string? = users.findLast(name => name.startsWith("G"));
// "Gordon"error
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string = users.findLast(name => name.startsWith("G")); error[E0308]: type mismatch for `last`: expected `string`, found `string?`
at /src/main.tyr:2:7
const last: string = users.findLast(name => name.startsWith("G"));
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`findIndex()
Retorna o índice do primeiro elemento que satisfaz o predicado, ou -1.
findIndex(predicate: (element: T) => boolean): i64const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item === "banana");
// 1error
const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item.length); error[E0308]: type mismatch for `return`: expected `boolean`, found `usize`
at /src/main.tyr:2:44
const index: i64 = items.findIndex(item => item.length);
^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`findLastIndex()
Retorna o índice do último elemento que satisfaz o predicado, ou -1.
findLastIndex(predicate: (element: T) => boolean): i64const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n === 2);
// 3error
const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:52
const lastIdx: i64 = duplicates.findLastIndex(n => n);
^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`some()
Verifica se ao menos um elemento satisfaz uma condição.
some(predicate: (element: T) => boolean): booleanconst ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age < 18);
// trueerror
const ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age * 2); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:44
const hasMinor: boolean = ages.some(age => age * 2);
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`every()
Verifica se todos os elementos satisfazem uma condição.
every(predicate: (element: T) => boolean): booleanconst temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t >= 36.0 && t <= 37.5);
// trueerror
const temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t + 1); error[E0369]: operator `+` cannot be applied to `f64` and `integer literal`
at /src/main.tyr:2:52
const allNormal: boolean = temperatures.every(t => t + 1);
^^^^^includes()
Verifica se um valor específico existe no array.
includes(value: T): booleanconst fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes("banana");
// trueerror
const fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes(42); error[E0308]: type mismatch for `includes`: expected `string`, found `integer literal`
at /src/main.tyr:2:28
const hasBanana: boolean = fruits.includes(42);
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`equals()
Compara dois arrays elemento a elemento: mesmo comprimento, mesmos elementos, mesma ordem. === e !== não comparam arrays; o compilador reporta E0369 e aponta para cá.
equals(other: T[]): booleanconst left: i32[] = [1, 2, 3];
const right: i32[] = [1, 2, 3];
const same: boolean = left.equals(right);
// true
const reordered: boolean = left.equals([3, 2, 1]);
// falseerror
const grid: i32[][] = [[1], [2]];
const same: boolean = grid.equals([[1], [2]]); error[E0277]: array method `equals` compares arrays of numbers, `boolean`, `char` or `string`, but the elements are `i32[]`
at /src/main.tyr:2:23
const same: boolean = grid.equals([[1], [2]]);
^^^^^^^^^^^^^^^^^^^^^^^indexOf()
Retorna o primeiro índice de um valor, ou -1 se não encontrado.
indexOf(value: T, fromIndex?: i64): i64const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf(2);
// 1error
const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf("2"); error[E0308]: type mismatch for `indexOf`: expected `i32`, found `string`
at /src/main.tyr:2:20
const first: i64 = digits.indexOf("2");
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`lastIndexOf()
Retorna o último índice de um valor, ou -1 se não encontrado.
lastIndexOf(value: T, fromIndex?: i64): i64const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf(2);
// 3error
const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf("2"); error[E0308]: type mismatch for `lastIndexOf`: expected `i32`, found `string`
at /src/main.tyr:2:19
const last: i64 = digits.lastIndexOf("2");
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Janelas, Acumulação e Matrizes
windows()
windows(size) retorna cópias sobrepostas de size elementos consecutivos. O receiver não muda; windows(0) é rejeitado e um tamanho maior que o array retorna um array vazio.
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) retorna o acumulador inicial seguido de cada valor acumulado. A callback recebe o acumulador e o elemento atual, e o receiver não muda.
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) retorna pares na ordem lexicográfica do receiver e do argumento. Qualquer entrada vazia produz um resultado vazio, e o receiver não muda.
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 o receiver e o argumento em uma array de pares (T, U)[], em que T é o tipo elementar do receiver e U é o tipo elementar do argumento. O comprimento do resultado é igual ao das duas entradas, que precisam ser iguais; as arrays fonte não mudam.
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);
}Comprimentos diferentes lançam um ZipError recuperável (code ERR_ARRAY_ZIP_MISMATCH) em vez de abortar, então a chamada precisa ser coberta por um catch ou por uma cláusula throws ZipError na função que a contém:
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() transforma uma matriz retangular em colunas. Matrizes vazias e matrizes com linhas de largura zero retornam arrays vazios; linhas irregulares falham antes de produzir um resultado parcial.
const matrix: i32[][] = [[1, 2], [3, 4], [5, 6]];
const columns: i32[][] = matrix.transpose(); // [[1, 3, 5], [2, 4, 6]]
print(columns);unique()
unique() retorna a primeira ocorrência de cada valor distinto na ordem de entrada. Ele não altera o receiver e usa a política nativa de igualdade para strings e números.
const values: i32[] = [3, 1, 3, 2, 1];
const distinct: i32[] = values.unique(); // [3, 1, 2]
print(distinct);uniqueBy()
uniqueBy(selector) mantém o primeiro elemento para cada chave hashable distinta. O seletor pode ser o nome de um campo para elementos objeto, uma callback explícita ou uma expressão implícita, na qual o tipo do elemento é inferido automaticamente.
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) cria um mapa de cada chave hashable para um array de elementos na ordem original. O seletor pode ser o nome de um campo para elementos objeto, uma callback explícita ou uma expressão implícita, na qual o tipo do elemento é inferido automaticamente. A primeira implementação exige elementos Copy para que cada grupo mantenha seus valores com segurança.
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 & Reordenação
flat()
Achata arrays aninhados em um nível.
flat(): T[]const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: i32[] = matrix.flat();
// [1, 2, 3, 4, 5]error
const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: string[] = matrix.flat(); error[E0308]: type mismatch for `flat`: expected `string[]`, found `i32[]`
at /src/main.tyr:2:7
const flat: string[] = matrix.flat();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`flatMap()
Mapeia cada elemento para um array e achata o resultado em um nível.
flatMap<U>(callback: (element: T) => U[]): U[]const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence.split(" "));
// ["hello", "world", "goodbye", "moon"]error
const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence); error[E0308]: `flatMap` callback must return an array, found `string`
at /src/main.tyr:2:25
const words: string[] = sentences.flatMap(sentence => sentence);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`sort()
Ordena o array in place usando uma função de comparação.
sort(compare?: (left: T, right: T) => i32): thislet numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left - right);
// [4, 8, 15, 23, 42]error
let numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left < right); error[E0308]: type mismatch for `return`: expected `i32`, found `boolean`
at /src/main.tyr:2:31
numbers.sort((left, right) => left < right);
^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`toSorted()
Retorna uma nova cópia ordenada sem modificar o original.
toSorted(compare?: (left: T, right: T) => i32): T[]const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left - right);
// [4, 8, 15, 23, 42]
// original is unchangederror
const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left > right); error[E0308]: type mismatch for `return`: expected `i32`, found `boolean`
at /src/main.tyr:2:58
const sorted: i32[] = original.toSorted((left, right) => left > right);
^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`sortBy()
Ordena um array in place por um campo resolvido estaticamente. A chave deve ser um literal string com o nome de um campo numérico, booleano, de caractere ou string. O segundo argumento é opcional: a ordem padrão é crescente e "desc" seleciona a ordem decrescente.
sortBy(key: keyof T, order?: "asc" | "desc"): thisinterface Score {
name: string;
points: i32;
}
let scores: Score[] = [
{ name: "Ada", points: 30 },
{ name: "Grace", points: 10 },
{ name: "Linus", points: 20 },
];
scores.sortBy("points"); // [{ name: "Grace", points: 10 }, { name: "Linus", points: 20 }, { name: "Ada", points: 30 }]
scores.sortBy("points", "desc"); // [{ name: "Ada", points: 30 }, { name: "Linus", points: 20 }, { name: "Grace", points: 10 }]O campo é resolvido em compile-time, então o loop de merge sort estável gerado lê o campo diretamente sem reflexão em runtime. sortBy() exige um receiver mutável em let e executa em O(n log n), com O(n) de espaço auxiliar.
sortedBy()
Retorna uma cópia ordenada por um campo resolvido estaticamente e mantém o receiver inalterado. O segundo argumento é opcional: a ordem padrão é crescente e "desc" seleciona a ordem decrescente. A primeira versão exige que os campos do elemento sejam Copy, evitando uma cópia rasa insegura de valores possuídos. Ela usa merge sort estável O(n log n), com O(n) de espaço auxiliar.
sortedBy(key: keyof T, order?: "asc" | "desc"): T[]interface Coordinate {
x: i32;
y: i32;
}
const points: Coordinate[] = [
{ x: 3, y: 9 },
{ x: 1, y: 4 },
{ x: 2, y: 7 },
];
const byX: Coordinate[] = points.sortedBy("x"); // [{ x: 1, y: 4 }, { x: 2, y: 7 }, { x: 3, y: 9 }]
const byYDesc: Coordinate[] = points.sortedBy("y", "desc"); // [{ x: 3, y: 9 }, { x: 2, y: 7 }, { x: 1, y: 4 }]reverse()
Inverte a ordem dos elementos in place.
reverse(): thislet stack: i32[] = [1, 2, 3];
stack.reverse();
// [3, 2, 1]error
const stack: i32[] = [1, 2, 3];
stack.reverse(); error[E0384]: cannot call mutating method `reverse` on immutable array `stack`
at /src/main.tyr:2:1
stack.reverse();
^^^^^
help: declare the binding with `let` to allow assignmentrotate()
Rotaciona o array in place. Valores positivos rotacionam para a esquerda; valores negativos rotacionam para a direita. O valor é normalizado pelo comprimento do array, e arrays vazios ou com um único elemento não mudam.
rotate(amount: i64): thislet values: i32[] = [1, 2, 3, 4, 5];
values.rotate(2); // [3, 4, 5, 1, 2]
values.rotate(-1); // [2, 3, 4, 5, 1]rotate() exige um receiver mutável em let e executa em O(n) com espaço auxiliar O(1), sem alocar um segundo array.
toReversed()
Retorna uma nova cópia com ordem invertida sem modificar o original.
toReversed(): T[]const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: string[] = days.toReversed();
// ["Wed", "Tue", "Mon"]
// days is unchangederror
const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: i32[] = days.toReversed(); error[E0308]: type mismatch for `reversed`: expected `i32[]`, found `string[]`
at /src/main.tyr:2:7
const reversed: i32[] = days.toReversed();
^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`random()
Retorna um T selecionado uniformemente. Um array vazio aborta em runtime.
random(): Tconst fruits = ["grape", "banana", "orange", "strawberry"];
const chosen = fruits.random();
print(chosen); // "orange"error
const fruits: string[] = [];
const chosen = fruits.random(); error[E0606]: array.random requires at least 1 element(s), found 0
at /src/main.tyr:2:16
const chosen = fruits.random();
^^^^^^shuffle()
Retorna um novo array embaralhado uniformemente sem modificar o receptor. Arrays com menos de dois elementos abortam em runtime.
shuffle(): T[]const fruits = ["grape", "banana", "orange", "strawberry"];
const shuffled = fruits.shuffle();
print(shuffled); // ["banana", "strawberry", "grape", "orange"]error
const value = [1];
const shuffled = value.shuffle(); error[E0606]: array.shuffle requires at least 2 element(s), found 1
at /src/main.tyr:2:18
const shuffled = value.shuffle();
^^^^^sample()
Retorna um novo array com count elementos selecionados uniformemente. count deve estar entre 1 e o tamanho do receptor, inclusive. Sem opções, posições de origem não se repetem. { repeat: true } permite repetições de posições, mas não as garante.
sample(count: usize, options?: { repeat?: boolean }): T[]const teams = ["Arsenal", "Barcelona", "Bayern Munich", "Inter Milan"];
const distinct = teams.sample(2);
const independent = teams.sample(2, { repeat: true });
print(distinct); // ["Bayern Munich", "Barcelona"]
print(independent); // ["Inter Milan", "Inter Milan"]error
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const none = teams.sample(0); error[E0606]: sample count 0 is out of bounds: valid counts are 1 to 3 (length 3)
at /src/main.tyr:2:27
const none = teams.sample(0);
^error
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const tooMany = teams.sample(4); error[E0606]: sample count 4 is out of bounds: valid counts are 1 to 3 (length 3)
at /src/main.tyr:2:30
const tooMany = teams.sample(4);
^Fatiamento
slice()
Extrai uma cópia de um subarray contíguo.
slice(start?: i64, end?: i64): T[]const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: string[] = letters.slice(1, 4);
// ["b", "c", "d"]error
const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: i32[] = letters.slice(1, 4); error[E0308]: type mismatch for `middle`: expected `i32[]`, found `string[]`
at /src/main.tyr:2:7
const middle: i32[] = letters.slice(1, 4);
^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Indexar com um Range é açúcar para .slice(): arr[a..b] é arr.slice(a, b), e toda forma aberta também funciona, arr[a..], arr[..b], arr[..=b] e o range completo arr[..]. Assim como .slice(), isso sempre copia para um array novo; arrays de tyrus ainda não têm representação de fatia emprestada sem cópia.
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 o array em dois arrays em um índice dado.
splitAt(index: i64): [T[], T[]]const letters: string[] = ["a", "b", "c", "d", "e"];
const parts: [string[], string[]] = letters.splitAt(2);
// [["a", "b"], ["c", "d", "e"]]error
const letters: string[] = ["a", "b"];
const parts: [string[], string[]] = letters.splitAt(10); error[E0606]: splitAt index 10 is out of bounds: valid indices are 0 to 2 (length 2)
at /src/main.tyr:2:53
const parts: [string[], string[]] = letters.splitAt(10);
^^splitAt sempre retorna dois arrays comuns de tamanho dinâmico ([T[], T[]]), inclusive quando chamado em um array de tamanho fixo. index pode ser igual ao comprimento do array, produzindo uma segunda metade vazia, mas um índice maior é erro de compilação quando o comprimento do array é conhecido estaticamente, e abort em tempo de execução caso contrário.
Agregação
count()
Retorna o comprimento, ou conta ocorrências de um valor ou predicado.
count(value?: T | (element: T) => boolean): i64const numbers: i32[] = [1, 2, 3, 4, 5, 6];
print(numbers.count()); // 6
print(numbers.count(3)); // 1
print(numbers.count(value % 2 === 0)); // 3
print(numbers.count(value > 3)); // 3error
const numbers: i32[] = [1, 2, 3, 4, 5, 6];
const total: i64 = numbers.count(value => value.toString()); error[E0282]: cannot infer type of parameter `value`
at /src/main.tyr:2:43
const total: i64 = numbers.count(value => value.toString());
^^^^^
error[E0599]: no method named `toString` for type `<inferred>`
at /src/main.tyr:2:43
const total: i64 = numbers.count(value => value.toString());
^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type
error[E0308]: `count` expects a value assignable to `i32`, found `(<inferred>) => void`
at /src/main.tyr:2:34
const total: i64 = numbers.count(value => value.toString());
^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`
error[E0308]: type mismatch for `total`: expected `i64`, found `usize`
at /src/main.tyr:2:7
const total: i64 = numbers.count(value => value.toString());
^^^^^
help: `usize` does not convert to `i64` on its own; write the conversion explicitly with `as i64`count() retorna o comprimento; count(valor) conta elementos iguais a valor; count(condição), uma expressão comum referenciando exatamente um identificador ainda não declarado no escopo atual, vira uma condição implícita por elemento, açúcar para count((implicitParam): boolean => condição) sem precisar escrever nenhuma arrow function. Um identificador que já resolve no escopo não é livre, então a expressão é checada como uma chamada comum count(valor), comparar seu resultado (constante) boolean contra o tipo do elemento é erro de compilação citando o identificador que sombreou o parâmetro implícito. Uma expressão referenciando mais de um identificador não declarado também é erro de compilação, já que o açúcar só introduz um parâmetro implícito.
sum()
Retorna a soma de todos os elementos numéricos usando o tipo dos elementos do array. Um array numérico vazio retorna o valor zero desse tipo.
sum(): Tconst values: i32[] = [2, 3, 4];
const total = values.sum(); // inferred as i32
print(total); // 9
const empty: i32[] = [];
print(empty.sum()); // 0sum() é rejeitado para tipos de elemento não numéricos e é compilado como um loop nativo direto, sem callback ou despacho ao runtime por elemento.
product()
Retorna o produto de todos os elementos numéricos usando o tipo dos elementos do array. Um array numérico vazio retorna o valor um desse tipo.
product(): Tconst values: i32[] = [2, 3, 4];
const product = values.product(); // inferred as i32
print(product); // 24
const empty: i32[] = [];
print(empty.product()); // 1product() segue as mesmas regras de tipo numérico e loop nativo de sum().
avg()
Retorna a média aritmética dos elementos numéricos. Arrays de inteiros, f32 e f64 retornam f64?; arrays de f128 retornam f128?. Um array vazio produz ausência.
avg(): f64? | f128?const values: i32[] = [2, 3, 4];
const average = values.avg(); // inferred as f64?
print(average ?? 0.0); // 3.0
const empty: i32[] = [];
print(empty.avg() ?? 0.0); // 0.0O resultado opcional deve ser tratado com ??, narrowing ou outra operação válida de opcionais antes do uso numérico direto.
sumBy()
Retorna a soma de um campo numérico em todos os elementos. A chave deve ser um literal de string nomeando um campo numérico.
sumBy(key: string): T[K]interface Item {
name: string;
quantity: i32;
price: f64;
}
const items: Item[] = [
{ name: "Widget", quantity: 3, price: 25.0 },
{ name: "Gadget", quantity: 1, price: 99.99 }
];
const totalQuantity = items.sumBy("quantity"); // 4 (i32)
const totalPrice = items.sumBy("price"); // 124.99 (f64)avgBy()
Retorna a média aritmética de um campo numérico em todos os elementos. A chave deve ser um literal de string nomeando um campo numérico. Sempre retorna f64? (ou f128? para campos f128).
avgBy(key: string): f64? | f128?const items: Item[] = [
{ name: "Widget", quantity: 3, price: 25.0 },
{ name: "Gadget", quantity: 1, price: 99.99 }
];
const avgPrice = items.avgBy("price"); // 62.495 (f64?)concat()
Mescla dois arrays em um novo.
concat(...items: (T | T[])[]): T[]const front: i32[] = [1, 2];
const back: i32[] = [3, 4];
const merged: i32[] = front.concat(back);
// [1, 2, 3, 4]error
const front: string[] = ["a", "b"];
const merged: string[] = front.concat(42); error[E0308]: type mismatch for `concat`: expected `string[]`, found `integer literal`
at /src/main.tyr:2:26
const merged: string[] = front.concat(42);
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`join()
Junta todos os elementos em uma única string usando um separador.
join(separator: string): stringconst parts: string[] = ["tyrus", "is", "native"];
const sentence: string = parts.join(" ");
// "tyrus is native"error
const numbers: i32[] = [1, 2, 3];
const text: string = numbers.join(", "); error[E0277]: `join` currently requires a `string[]` receiver
at /src/main.tyr:2:22
const text: string = numbers.join(", ");
^^^^^^^^^^^^^^^^^^Mutação
splice()
Remove, substitui ou insere elementos in place.
splice(start: i64, deleteCount?: i64, ...items: T[]): T[]let values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8);
print(values[1]);
print(removed[0]);error
const values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8); error[E0384]: cannot call mutating method `splice` on immutable array `values`
at /src/main.tyr:2:24
const removed: i32[] = values.splice(1, 2, 7, 8);
^^^^^^
help: declare the binding with `let` to allow assignmentsplice(start, deleteCount?, ...items) modifica o receptor e retorna um novo array com os elementos removidos. Índices iniciais negativos contam a partir do fim, a remoção é limitada ao intervalo disponível e os valores inseridos devem corresponder ao tipo dos elementos do array.
fill()
Substitui todos os elementos por um valor fixo.
fill(value: T): thislet buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill(7);
// [7, 7, 7, 7, 7]error
let buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill("x"); error[E0308]: type mismatch for `fill`: expected `i32`, found `string`
at /src/main.tyr:2:1
buffer.fill("x");
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`copyWithin()
Copia uma seção contígua do array para outra posição no mesmo array.
copyWithin(target: i64, start: i64, end?: i64): thislet data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin(0, 3);
// [4, 5, 3, 4, 5]error
let data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin("x", 3); error[E0308]: type mismatch for `copyWithin`: expected `i64`, found `string`
at /src/main.tyr:2:1
data.copyWithin("x", 3);
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Acesso & Iteração
first()
Retorna o primeiro elemento como T?. Um array vazio produz ausência. A anotação de tipo é opcional: quando values é i32[], o tyrus infere i32? automaticamente. Optional<i32> é a forma explícita equivalente.
first(): T?const values: i32[] = [10, 20, 30];
const firstValue = values.first(); // inferred as i32?
const explicitFirst: Optional<i32> = values.first();
if (firstValue) {
print(firstValue + 1); // 11
}
const firstOrDefault: i32 = firstValue ?? 0;
print(firstOrDefault);
const empty: i32[] = [];
print(empty.first() ?? -1); // -1T? é intencional: first() retorna um valor, não uma coleção, e continua O(1) sem alocar um array vazio como resultado. O uso direto como i32 é rejeitado até que um if, ??, ternário, optional chaining ou outra operação válida de narrowing trate a ausência.
last()
Retorna o último elemento como T?. Um array vazio produz ausência, e o tyrus infere automaticamente o tipo opcional do elemento quando a anotação é omitida.
last(): T?const values: i32[] = [10, 20, 30];
const lastValue = values.last(); // inferred as i32?
const explicitLast: Optional<i32> = values.last();
const lastOrDefault: i32 = lastValue ? lastValue : 0;
print(lastOrDefault);
const empty: i32[] = [];
print(empty.last() ?? -1); // -1last() segue as mesmas regras de ausência e narrowing de first(), lendo o elemento final em O(1) sem alocar um array de resultado.
at()
Retorna o elemento em um índice, suportando indexação negativa a partir do fim.
at(index: i64): Tconst main = (): void => {
const colors: string[] = ["red", "green", "blue"];
const last: string? = colors.at(-1);
print(last ?? "none"); // blue
};error
const main = (): void => {
const colors: string[] = ["red", "green", "blue"];
const last: string? = colors.at("x");
};error[E0308]: type mismatch for `at`: expected `i64`, found `string`
at /src/main.tyr:3:27
const last: string? = colors.at("x"); // [!code error]
^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`keys()
Retorna um iterador sobre os índices do array.
keys(): Iterable<i64>const items: string[] = ["x", "y", "z"];
for (const index of items.keys()) {
print(index); // 0, 1, 2
}error
const items: string[] = ["x", "y", "z"];
const keys: i64[] = items.keys(); error[E0308]: type mismatch for `keys`: expected `i64[]`, found `usize[]`
at /src/main.tyr:2:7
const keys: i64[] = items.keys();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`values()
Retorna um iterador sobre os valores do array.
values(): Iterable<T>const items: i32[] = [10, 20, 30];
let total: i32 = 0;
for (const value of items.values()) {
total += value;
}
print(total); // 60error
const items: i32[] = [10, 20, 30];
const vals: string[] = items.values(); error[E0308]: type mismatch for `vals`: expected `string[]`, found `i32[]`
at /src/main.tyr:2:7
const vals: string[] = items.values();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`entries()
Retorna um iterador sobre pares índice-valor.
entries(): Iterable<[i64, T]>const fruits: string[] = ["apple", "banana", "cherry"];
for (const [index, fruit] of fruits.entries()) {
print(`${index}: ${fruit}`);
// 0: apple
// 1: banana
// 2: cherry
}error
const fruits: string[] = ["apple", "banana", "cherry"];
const entries: [i64, string][] = fruits.entries(); error[E0308]: type mismatch for `entries`: expected `[i64, string][]`, found `[usize, string][]`
at /src/main.tyr:2:7
const entries: [i64, string][] = fruits.entries();
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Cópia Imutável
with()
Retorna um novo array com um único elemento substituído em um índice dado.
with(index: i64, value: T): T[]const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, "yellow");
// ["red", "yellow", "blue"]
// colors is unchangederror
const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, 42); error[E0308]: type mismatch for `with`: expected `string`, found `integer literal`
at /src/main.tyr:2:27
const updated: string[] = colors.with(1, 42);
^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Toggle
toggle()
Adiciona um elemento ao array se ele não estiver presente e o remove se estiver presente, retornando um novo array e nunca mutando o receiver.
toggle(item: T): T[]toggle(item: T, key: string): T[]const values: i32[] = [1, 2, 3];
print(values.toggle(4)); // [1, 2, 3, 4]
print(values.toggle(2)); // [1, 3]
print(values); // [1, 2, 3]Quando um nome de campo key é informado, a comparação é feita por esse campo em vez do elemento como um todo. O campo deve existir no tipo do elemento.
interface Pet {
name: string;
age: i32;
}
const pets: Pet[] = [
{ name: "rex", age: 2 },
{ name: "mia", age: 5 },
];
const adopted: Pet[] = pets.toggle({ name: "rex", age: 99 }, "name");
print(adopted.length); // 1toggleAll()
Aplica o mesmo comportamento de adicionar ou remover a cada elemento do array argumento, preservando a ordem. Não muta nada.
toggleAll(items: T[]): T[]const values: i32[] = [1, 2, 3];
print(values.toggleAll([2, 4])); // [1, 3, 4]Encadeamento
Métodos funcionais se encadeiam em pipelines de dados legíveis:
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