Skip to content

11 · Iterators and Pipes

Build values on demand

Prefix a collection builder with iter to obtain Iter<T>. Source iteration and item expressions begin when a consumer requests values. Filtering and nested loops retain their order; stopping early closes the owned producers.

On this page

Prefix a collection builder with iter to obtain Iter<T>. Source iteration and item expressions begin when a consumer requests values. Filtering and nested loops retain their order; stopping early closes the owned producers.

Complete example

Build values on demand.

01-lazy-builders.zolo
Playground
// Computing the first two invoice totals never visits the third invoice.

let mut visits = 0
let mut sources = 0
let mut closed = 0

fn* invoices() -> int {
    sources += 1
    defer { closed += 1 }
    yield 10
    yield 20
    yield 30
}

fn tax(total: int) -> int {
    visits += 1
    total + 2
}

let totals: Iter<int> = iter [for total in invoices() => tax(total)]
assert(visits == 0)
assert(sources == 0)
let first = totals.take(2).collect()
assert(first.len() == 2)
assert(first[0] == 12)
assert(first[1] == 22)
assert(visits == 2)
assert(sources == 1)
assert(closed == 1)

enum Payment { Paid(int), Pending }
let payments: [Payment] = [.Pending, .Paid(5), .Paid(10)]
let paid = iter [for case .Paid(amount) in payments => if amount > 5 => amount]
let paid_values = paid.collect()
assert(paid_values.len() == 1)
assert(paid_values[0] == 10)

let pairs = iter [for left in [1, 2] => for right in [3, 4] => left * right]
let pair_values = pairs.collect()
assert(pair_values.len() == 4)
assert(pair_values[0] == 3)
assert(pair_values[1] == 4)
assert(pair_values[2] == 6)
assert(pair_values[3] == 8)
print("lazy totals: {first}")

Reference

Reference · Source program

zolo run examples/features/75-syntax-four-async/01-lazy-builders.zolo --no-cache

See also

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br