Skip to content

Iter Sources and Transformations

The Iter module works lazily: no element is processed until a terminal consumer (collect, fold, each) is called. This lets you compose transformations without allocating intermediate arrays.

Iter::range(start, end) produces a numeric sequence with an exclusive end — ideal as a pipeline source:

Empty ranges, using fold, and feeding a map; the end is exclusive.

03-iter-range.zolo
Playground
// Feature: `Iter.range` — lazy numeric sequence

// Syntax: `Iter::range(start, end)` (end exclusive).

// When to use: create numeric sources for iterator pipelines without

// materializing the whole array in memory.


use std::Iter

// Simple range 0..5.

let r = Iter::range(0, 5)
print(r.collect())

// expected: [0, 1, 2, 3, 4]


// Range collected to sum.

let sum = Iter::range(1, 11).fold(0, |acc, x| acc + x)
print("sum 1..10 = {sum}")

// expected: sum 1..10 = 55


// Empty range when start >= end.

let empty = Iter::range(5, 5)
print(empty.collect())

// expected: []


// Range feeding a map.

let squares = Iter::range(1, 6).map(|x| x * x).collect()
print(squares)
// expected: [1, 4, 9, 16, 25]

map transforms each element 1-to-1; filter keeps only the elements that satisfy the predicate. Both are lazy and can be chained — the source is traversed only once:

Numeric map, filter for evens, combined map + filter; filter with strings via Iter::from.

04-iter-map-filter.zolo
Playground
// Feature: `Iter.map` and `Iter.filter`

// Syntax: `it.map(|x| ...)`, `it.filter(|x| bool)`.

// When to use: transform and select elements lazily. Nothing happens

// until `Iter.collect` (or another terminal consumer).


use std::Iter

// map — 1-to-1 transformation.

let doubled = Iter::range(1, 6).map(|x| x * 2)
print(doubled.collect())

// expected: [2, 4, 6, 8, 10]


// filter — keeps only when the predicate is true.

let evens = Iter::range(1, 11).filter(|x| x % 2 == 0)
print(evens.collect())

// expected: [2, 4, 6, 8, 10]


// map + filter chained: lazy, walks the source only once.

let mapped = Iter::range(1, 11).map(|x| x * x)
let big_evens = mapped.filter(|x| x > 20)
print(big_evens.collect())

// expected: [25, 36, 49, 64, 81, 100]


// filter with strings.

let names = Iter::from(["Alice", "Bob", "Charlie", "Dan"])
let long_names = names.filter(|s| s.len() > 3)
print(long_names.collect())
// expected: ["Alice", "Charlie"]

enespt-br