Arrays
Nesta página
O array é a coleção mais básica do Zolo: uma lista ordenada de valores
acessíveis por posição (índice 0). O tipo é inferido como [T] a partir do
literal [a, b, c].
Indexação e tamanho são diretos:
Literal, indexação, push/pop, fatiamento, spread e operações funcionais.
01-arrays.zolo
// Feature: Arrays — 0-indexed ordered collection
// Syntax: `[a, b, c]`, indexing `arr[i]`, slicing `arr[i..j]`
// When to use: list of N values accessible by position, order
// matters, frequent append/pop.
use std::Array
// Literal and 0-based indexing.
let nums = [10, 20, 30, 40, 50]
print(nums[0]) // 10
print(nums[4]) // 50
print(nums.len()) // 5
// Type inferred as `[int]`. Explicit annotation:
let names: [str] = ["Alice", "Bob", "Carol"]
print(names[1]) // Bob
// Mutability: `let mut` + `Array.push/pop` or `.push()`.
let mut bag = [1, 2, 3]
bag.push(4)
bag.push(5)
print(bag) // [1, 2, 3, 4, 5]
let last = bag.pop()
print(last) // 5
print(bag) // [1, 2, 3, 4]
// Slicing by range — creates a new array.
let s = nums[0..3] // [10, 20, 30] exclusive
let t = nums[2..=4] // [30, 40, 50] inclusive
print(s)
print(t)
// Spread in literals.
let a = [1, 2]
let b = [3, 4]
let merged = [0, ...a, ...b, 5]
print(merged) // [0, 1, 2, 3, 4, 5]
// Functional operations (see also 05-functions/06-higher-order).
let doubled = Array::map([1, 2, 3], |x| x * 2)
let evens = Array::filter([1, 2, 3, 4], |x| x % 2 == 0)
let total = Array::reduce([1, 2, 3, 4], |acc, x| acc + x, 0)
print(doubled) // [2, 4, 6]
print(evens) // [2, 4]
print(total) // 10
// Sort and reverse — return a new array.
let desc = Array::sort([3, 1, 4, 1, 5, 9, 2]).reverse()
print(desc) // [9, 5, 4, 3, 2, 1, 1]
Alguns pontos importantes:
- Fatiamento com
[i..j](exclusivo) ou[i..=j](inclusivo) cria um novo array. - Spread
[...a, ...b]mescla arrays dentro de um novo literal. Array::map,Array::filtereArray::reduceretornam novos arrays sem alterar o original.
Desafio
Use Array::filter para filtrar os números ímpares de [1, 2, 3, 4, 5, 6]
e depois Array::reduce para somar o resultado. A soma deve ser 9.
Veja também