Reducción y Paginación
En esta página
fold es el reductor universal: recibe un acumulador inicial y un closure
|acc, x| nuevo_acc, colapsando toda la secuencia en un único valor. Suma,
producto, máximo y concatenación siguen el mismo patrón:
Suma, factorial, máximo y join de strings — todos expresados con fold.
05-iter-fold-reduce.zolo
// Feature: `Iter.fold` — reduction with an accumulator
// Syntax: `it.fold(init, |acc, x| new_acc)`.
// When to use: collapse an iterator into a single value (sum, product,
// max, concat, struct build, etc.).
use std::Iter
// Classic sum.
let total = Iter::range(1, 6).fold(0, |acc, x| acc + x)
print("sum = {total}")
// expected: sum = 15
// Product.
let prod = Iter::range(1, 6).fold(1, |acc, x| acc * x)
print("5! = {prod}")
// expected: 5! = 120
// Maximum (init = conceptually the first element; here we use a small
// known value).
let mx = Iter::from([3, 1, 4, 1, 5, 9, 2, 6]).fold(0, |acc, x| {
if x > acc { return x }
return acc
})
print("max = {mx}")
// expected: max = 9
// Concatenate strings.
let words = Iter::from(["zolo", "is", "fun"])
let joined = words.fold("", |acc, w| {
if acc == "" { return w }
return acc + " " + w
})
print(joined)
// expected: zolo is fun
take(n) conserva solo los primeros n elementos; skip(n) descarta los
primeros n. Combinados, funcionan como paginación sobre cualquier iterador,
incluyendo ranges largos o infinitos:
take, skip, ventana skip+take; comportamiento cuando la fuente es menor que n.
06-iter-take-skip.zolo
// Feature: `Iter.take` and `Iter.skip`
// Syntax: `it.take(n)` keeps the first n; `it.skip(n)`
// drops the first n.
// When to use: paginate, limit infinite ranges, skip headers.
use std::Iter
// take — grabs the first 5.
let first5 = Iter::range(0, 100).take(5)
print(first5.collect())
// expected: [0, 1, 2, 3, 4]
// skip — drops the first 3.
let after3 = Iter::range(0, 8).skip(3)
print(after3.collect())
// expected: [3, 4, 5, 6, 7]
// take + skip = window [3, 6) over 0..100.
let window = Iter::range(0, 100).skip(3).take(3)
print(window.collect())
// expected: [3, 4, 5]
// take on a finite source: truncates when it runs out before n.
let small = Iter::range(0, 3).take(10)
print(small.collect())
// expected: [0, 1, 2]
// skip beyond size — returns empty.
let nothing = Iter::range(0, 3).skip(10)
print(nothing.collect())
// expected: []
Desafío
Usa Iter::range(0, 100).skip(10).take(5) para obtener la "segunda página" de
tamaño 5 de una lista de 0 a 99. Verifica el resultado esperado.
Consulta también