// DOCS NAVIGATION
std.collections — Coleções_
SOURCE: content/docs/reference/05-stdlib.md — 05 Stdlib / 5. std.collections — Coleções / Collections
PT-BR:
O módulo std.collections proVê listas dinâmicas via handles opacos (inteiros). Um handle é um identificador numérico para uma lista gerenciada pelo runtime. Não manipule handles diretamente.
EN-US:
The std.collections module provides dynamic lists via opaque handles (integers). A handle is a numeric identifier for a runtime-managed list. Do not manipulate handles directly.
import std.collections as col
Operações Básicas / Basic Operations
list_new() -> int
PT-BR: Cria uma nova lista vazia. Retorna o handle.
EN-US: Creates a new empty list. Returns the handle.
let lista = col.list_new()
// handle, ex: 1
list_push(handle: int, value: int) -> unit
let lista = col.list_new()
col.list_push(lista, 10)
col.list_push(lista, 20)
col.list_push(lista, 30)
list_len(handle: int) -> int
let n = col.list_len(lista)
// 3
list_get(handle: int, index: int) -> int
PT-BR: Retorna o elemento no índice. Retorna -1 se fora dos limites.
EN-US: Returns the element at the index. Returns -1 if out of bounds.
let v = col.list_get(lista, 0)
// 10
let oob = col.list_get(lista, 99)
// -1
list_set(handle: int, index: int, value: int) -> unit
col.list_set(lista, 0, 99)
// Substitui o elemento 0 por 99
list_pop(handle: int) -> int
PT-BR: Remove e retorna o último elemento. Retorna -1 se vazia.
EN-US: Removes and returns the last element. Returns -1 if empty.
let ultimo = col.list_pop(lista)
// 30
list_pop_front(handle: int) -> int
let primeiro = col.list_pop_front(lista)
// 10
list_insert_at(handle: int, index: int, value: int) -> unit
col.list_insert_at(lista, 1, 50)
// Insere 50 na posição 1
list_remove_at(handle: int, index: int) -> int
PT-BR: Remove o elemento no índice e o retorna. Retorna -1 se inválido.
EN-US: Removes the element at the index and returns it. Returns -1 if invalid.
let removido = col.list_remove_at(lista, 0)
list_contains(handle: int, value: int) -> bool
let tem = col.list_contains(lista, 20)
// true/false
list_index_of(handle: int, value: int) -> int
PT-BR: Retorna o índice da primeira ocorrência ou -1.
EN-US: Returns the index of the first occurrence or -1.
let idx = col.list_index_of(lista, 20)
// índice ou -1
list_sort(handle: int) -> unit
PT-BR: Ordena a lista em ordem crescente in-place.
EN-US: Sorts the list in ascending order in-place.
col.list_sort(lista)
list_clear(handle: int) -> unit
col.list_clear(lista)
// Remove todos os elementos
list_free(handle: int) -> unit
PT-BR: Libera a memória da lista. Importante: Chamar quando não precisar mais.
EN-US: Frees the list's memory. Important: Call when no longer needed.
col.list_free(lista)
// Libera recursos
list_free_all() -> int
PT-BR: Libera todas as listas alocadas. Retorna quantas foram liberadas.
EN-US: Frees all allocated lists. Returns how many were freed.
let liberadas = col.list_free_all()
Funções de Alta Ordem / Higher-Order Functions
list_map(handle: int, fn_ptr: int) -> int
PT-BR: Cria uma nova lista aplicando a função a cada elemento.
EN-US: Creates a new list by applying the function to each element.
Nota / Note:
fn_ptré um ponteiro para função obtido via conversão. O uso direto com closures SpectraLang está em desenvolvimento.
list_filter(handle: int, fn_ptr: int) -> int
PT-BR: Cria uma nova lista com apenas os elementos que satisfazem o predicado.
EN-US: Creates a new list with only elements satisfying the predicate.
list_reduce(handle: int, initial: int, fn_ptr: int) -> int
PT-BR: Reduz a lista a um único valor acumulando com a função.
EN-US: Reduces the list to a single value by accumulating with the function.
list_sort_by(handle: int, fn_ptr: int) -> unit
PT-BR: Ordena com comparador customizado. A função comparador deve retornar -1, 0, ou 1.
EN-US: Sorts with a custom comparator. The comparator function must return -1, 0, or 1.
Exemplo Completo / Complete Example
module usando_colecoes
import std.collections as col
from std.io import println
import std.convert
public func main() {
// Criar lista / Create list
let lista = col.list_new()
// Adicionar elementos / Add elements
col.list_push(lista, 5)
col.list_push(lista, 3)
col.list_push(lista, 8)
col.list_push(lista, 1)
col.list_push(lista, 9)
col.list_push(lista, 2)
println(f"Tamanho: {col.list_len(lista)}")
// 6
// Ordenar / Sort
col.list_sort(lista)
// Imprimir todos / Print all
let i = 0
while i < col.list_len(lista) {
println(std.convert.int_to_string(col.list_get(lista, i)))
i = i + 1
}
// 1, 2, 3, 5, 8, 9
// Verificar / Check
println(f"Contém 5: {col.list_contains(lista, 5)}")
// true
println(f"Índice de 8: {col.list_index_of(lista, 8)}")
// 4
// Liberar / Free
col.list_free(lista)
}