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

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

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

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

tyrus
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

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

Propriedades ​

MembroTipoComportamento
lengthusizeQuantidade atual de elementos.
capacityusizeArmazenamento 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étodoAssinaturaComportamento
pushpush(...items: T[]): usizeAdiciona valores ao final e retorna o novo tamanho.
poppop(): T?Remove e retorna o último valor, ou ausência.
unshiftunshift(...items: T[]): usizeAdiciona valores no início e retorna o novo tamanho.
shiftshift(): T?Remove e retorna o primeiro valor, ou ausência.
splicesplice(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étodoAssinaturaComportamento
Array.ofArray.of(...items: T[]): T[]Cria um array com os argumentos recebidos.
Array.fromArray.from(items: T[]): T[]Copia um array para um array de tamanho dinâmico.
Array.withCapacityArray.withCapacity(capacity: usize): T[]Cria um array vazio com capacidade reservada.
Array.isArrayArray.isArray(value: unknown): booleanVerifica se um valor é um array.

Métodos Funcionais ​

CategoriaMétodos
Iteração & Transformaçãomap(), filter(), partition(), reduce(), reduceRight(), forEach()
Janelas e Matrizeswindows(), scan(), cartesianProduct(), zip(), transpose()
Deduplicação e Agrupamentounique(), uniqueBy(), groupBy()
Toggletoggle(), toggleAll()
Busca & Testefind(), findLast(), findIndex(), findLastIndex(), some(), every(), includes(), equals(), indexOf(), lastIndexOf()
Flatten & Reordenaçãoflat(), flatMap(), sort(), toSorted(), sortBy(), sortedBy(), reverse(), rotate(), toReversed(), random(), shuffle(), sample()
Fatiamentoslice(), splitAt()
Agregaçãosum(), product(), avg(), sumBy(), avgBy(), count(), concat(), join()
Mutaçãosplice(), fill(), copyWithin()
Acesso & Iteraçãofirst(), last(), at(), keys(), values(), entries()
Cópia Imutávelwith()

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.

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

Seleciona elementos que satisfazem um predicado.

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

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

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.

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

Um campo desconhecido é rejeitado em tempo de compilação.

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 mais complexos, use uma arrow function explícita. Ela pode receber o elemento, seu índice e o 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() 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.

Assinaturareduce<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 em um único valor, da direita para a esquerda.

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

Executa um callback para cada elemento. O valor de retorno é descartado.

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

Busca & Teste ​

find() ​

Retorna o primeiro elemento que satisfaz um predicado, ou ausência se nenhum satisfizer.

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

Retorna o último elemento que satisfaz um predicado, ou ausência se nenhum satisfizer.

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

Retorna o índice do primeiro elemento que satisfaz o predicado, ou -1.

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

Retorna o índice do último elemento que satisfaz o predicado, ou -1.

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

Verifica se ao menos um elemento satisfaz uma condição.

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

Verifica se todos os elementos satisfazem uma condição.

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

Verifica se um valor específico existe no array.

Assinaturaincludes(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 dois arrays elemento a elemento: mesmo comprimento, mesmos elementos, mesma ordem. === e !== não comparam arrays; o compilador reporta E0369 e aponta para cá.

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

Retorna o primeiro índice de um valor, ou -1 se não encontrado.

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

Retorna o último índice de um valor, ou -1 se não encontrado.

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

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.

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) retorna o acumulador inicial seguido de cada valor acumulado. A callback recebe o acumulador e o elemento atual, e o receiver não muda.

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) retorna pares na ordem lexicográfica do receiver e do argumento. Qualquer entrada vazia produz um resultado vazio, e o receiver não muda.

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

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

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:

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

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

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

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

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 & Reordenação ​

flat() ​

Achata arrays aninhados em um nível.

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

Mapeia cada elemento para um array e achata o resultado em um nível.

AssinaturaflatMap<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 o array in place usando uma função de comparação.

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

Retorna uma nova cópia ordenada sem modificar o original.

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

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

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.

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

Inverte a ordem dos elementos in place.

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

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.

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

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

Retorna um T selecionado uniformemente. Um array vazio aborta em runtime.

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

Retorna um novo array embaralhado uniformemente sem modificar o receptor. Arrays com menos de dois elementos abortam em runtime.

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

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.

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

Fatiamento ​

slice() ​

Extrai uma cópia de um subarray contíguo.

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

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 o array em dois arrays em um índice dado.

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

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

Assinaturasum(): 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() é 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.

Assinaturaproduct(): 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() 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.

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

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

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

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

Mescla dois arrays em um novo.

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

Junta todos os elementos em uma única string usando um separador.

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

Mutação ​

splice() ​

Remove, substitui ou insere elementos in place.

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

Assinaturafill(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 uma seção contígua do array para outra posição no mesmo array.

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

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.

Assinaturafirst(): 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? é 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.

Assinaturalast(): 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() 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.

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

Retorna um iterador sobre os índices do array.

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

Retorna um iterador sobre os valores do array.

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

Retorna um iterador sobre pares índice-valor.

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

Cópia Imutável ​

with() ​

Retorna um novo array com um único elemento substituído em um índice dado.

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

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.

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

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.

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 o mesmo comportamento de adicionar ou remover a cada elemento do array argumento, preservando a ordem. Não muta nada.

AssinaturatoggleAll(items: T[]): T[]
tyrus
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:

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