Nyx by Example

Iterator: enumerate()

enumerate() transforms any iterator into one that yields pairs of [index, value]. It is the idiomatic way to track the position of each element without managing a counter variable by hand.

Code

// Iteradores: enumerate() para obtener pares (índice, valor)

fn print_pair(idx: int, val: int) {
    print("[" + int_to_string(idx) + "] = " + int_to_string(val))
}

fn main() -> int {
    let frutas: Array = [10, 20, 30, 40, 50]

    // enumerate() retorna un iterador de pares {index, value}
    // Se puede iterar con for-in desempaquetando idx y val
    let enumerado: Array = frutas.iter().enumerate().collect()

    // Cada elemento es un array [indice, valor]
    var i: int = 0
    while i < enumerado.length() {
        let par: Array = enumerado[i]
        let idx: int = par[0]
        let val: int = par[1]
        print_pair(idx, val)
        i = i + 1
    }

    // También se puede combinar con otros adapters
    let primeros: Array = frutas.iter().enumerate().take(3).collect()
    print("primeros 3 enumerados: " + int_to_string(primeros.length()))

    return 0
}

Output

[0] = 10
[1] = 20
[2] = 30
[3] = 40
[4] = 50
primeros 3 enumerados: 3

Explanation

Calling .iter() on an array produces a lazy iterator. Chaining .enumerate() wraps each item into a two-element array [index, value], and .collect() materializes the whole pipeline into a concrete Array. Each element of the result is itself an array, so par[0] gives the index and par[1] gives the original value.

Because enumerate() is just another iterator adapter, it composes freely with the rest of the iterator API. The second pipeline in this example adds .take(3) after .enumerate() to collect only the first three indexed pairs — demonstrating that adapters can be stacked in any order.

This pattern eliminates the error-prone pattern of maintaining a separate counter variable alongside a loop, and makes the intent of the code immediately clear to any reader.

← Previous Next →

Source: examples/by-example/31-iterator-enumerate.nx