Iterator: take() and skip()
take(n) limits an iterator to its first n elements, while skip(n) discards the first n and yields the rest. Together they form the building blocks of windowing, slicing, and pagination over any sequence.
Code
// Iteradores: skip() y take() para componer pipelines de datos
fn main() -> int {
let nums: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// skip(2): omitir los primeros 2 elementos
let sin_primeros2: Array = nums.iter().skip(2).collect()
print("skip(2): " + int_to_string(sin_primeros2.length()) + " elementos")
// take(3): tomar solo los primeros 3
let solo3: Array = nums.iter().take(3).collect()
print("take(3): " + int_to_string(solo3.length()) + " elementos")
let v0: int = solo3[0]
let v2: int = solo3[2]
print(" [0]=" + int_to_string(v0) + " [2]=" + int_to_string(v2))
// Combinacion: skip(2).take(3) — elementos 3, 4, 5
let ventana: Array = nums.iter().skip(2).take(3).collect()
print("skip(2).take(3): " + int_to_string(ventana.length()) + " elementos")
var i: int = 0
while i < ventana.length() {
let v: int = ventana[i]
print(" " + int_to_string(v))
i = i + 1
}
// Otro uso: paginar — página 2, tamaño 3
let pagina2: Array = nums.iter().skip(3).take(3).collect()
print("pagina 2 (skip 3, take 3): " + int_to_string(pagina2.length()) + " elementos")
return 0
}
Output
skip(2): 8 elementos take(3): 3 elementos [0]=1 [2]=3 skip(2).take(3): 3 elementos 3 4 5 pagina 2 (skip 3, take 3): 3 elementos
Explanation
skip(2) on a 10-element array yields elements at positions 2 through 9, giving 8 items. take(3) stops the iterator after the first 3 elements, producing [1, 2, 3] — so [0] is 1 and [2] is 3.
Chaining skip(2).take(3) first discards two elements, then limits the remainder to three — yielding [3, 4, 5]. This is the classic sliding window pattern. The order matters: take(3).skip(2) would instead give a single element.
The pagination example at the end shows a direct real-world use: to fetch page P of size N, write .skip((P-1) * N).take(N). Both adapters are lazy — no elements are allocated until .collect() is called.