Skip to content

Iteration

The Iterator and Iterable protocols, lazy adapters and what consumes them, collect(), and writing cursors for your own types.

for value in source is built on two stdlib traits. Iterable[T] says “you can ask me for a cursor”; Iterator[T] is the cursor itself, and yields Option[T] until it runs out.

fn main() void {
    names := ["ada", "grace", "alan"]

    for name in names {
        println(name)
    }
}

That loop desugars to names.iterator() followed by repeated next() calls until one returns None. Anything implementing either trait can appear on the right of in — lists, strings, maps, sets, windows ([]T from slice), ranges, streams, and your own types.

for is the only loop construct in Atoll. This page covers the iteration protocol and the operators that compose over it; the four for forms (for pat in x, for cond, for pat := expr, and bare for { }) are specified in Loops.

The two traits

Iterator[T] has one required method:

trait Iterator[T] {
    fn next(&mut self) Option[T]
}

Iterable[T] has an associated type and one required method:

trait Iterable[T] {
    type Iter: Iterator[T]
    fn iterator(&self) Iter
}

The split matters. An Iterable is a source and can be traversed many times, because each iterator() call hands back a fresh cursor. An Iterator is a position and is consumed as it advances.

fn main() void {
    values := [1, 2, 3]

    // `values` is Iterable — traversing it twice is fine.
    for v in values { println("first pass ${v}") }
    for v in values { println("second pass ${v}") }

    // A cursor is used up. The second `count()` sees an exhausted iterator.
    mut cursor := values.iterator()
    println("${cursor.count()}")   // 3
    println("${cursor.count()}")   // 0 — nothing left
}

Driving a cursor by hand

next() is the whole protocol. Everything else is built on it, and writing the loop out is always available:

fn main() void {
    readings := [12, 7, 40, 3, 25]

    mut cursor := readings.iterator()
    mut total := 0
    mut done := false
    for !done {
        match cursor.next() {
            Some(v) => { total = total + v }
            None => { done = true }
        }
    }
    println("total ${total}")
}

for v in cursor is the same loop with the match written for you, and works on a cursor as well as on a collection:

fn main() void {
    readings := [12, 7, 40, 3, 25]

    mut cursor := readings.iterator()
    for v in cursor {
        println("${v}")
    }
}

Consuming a builtin cursor

Iterator supplies default methods on top of next. On the stdlib’s own cursors — ListIter, SetIter, MapKeysIter, and friends — these lower and run today.

Method Consumption
count() Counts and exhausts the remainder
first() Pulls at most one element
last() Exhausts and returns the final element
any(f) / all(f) Stop as soon as the answer is decided
find(f) Stops at the first match
fn main() void {
    readings := [12, 7, 40, 3, 25]

    mut a := readings.iterator()
    println("any over 30? ${a.any(v => v > 30)}")

    mut b := readings.iterator()
    println("all positive? ${b.all(v => v > 0)}")

    mut c := readings.iterator()
    println("first over 20: ${c.find(v => v > 20) ?? -1}")

    mut d := readings.iterator()
    println("head ${d.first() ?? -1}")

    mut e := readings.iterator()
    println("tail ${e.last() ?? -1}")
}

Each of those takes a fresh iterator() because the previous one has been consumed. After a short-circuiting call the cursor sits just past the element that decided the answer — it is not rewound.

Iterator also declares for_each(f). It is real, but a non-capturing callback currently fails to lower with an internal error (ATOLL5001), so prefer for v in cursor, which has no such limitation.

Lazy adapters

A list’s map, filter, take, skip, take_while, skip_while, enumerate, zip, flat_map, flatten, scan and distinct are adapters, and so are the same methods on any Iterator: each wraps what it is called on in another cursor and visits nothing. Nothing runs until something consumes the pipeline — a for loop, a terminal, or a collector.

fn main() void {
    readings := [12, 7, 40, 3, 25, 61, 8]

    for v in readings.filter(v => v > 10).take(2) { println("${v}") }
}
Consumer Answers
count() how many elements there are
sum(), sum_of(f), average() the elements, or f of each, added up
fold(initial, f), reduce(initial, f) the elements folded into initial
min(), max(), min_by(f), max_by(f), min_of(f), max_of(f) the least or greatest, or None
any(p), all(p), none(p) whether the predicate holds; they stop at the first answer
find(p), find_index(p), first(), last(), contains(x) an element or its place, or None
for_each(f), join(sep), join_of(sep, f), join_with(sep, f) f of each, or the elements as text
collect() a new []T — or the Set[T] or Map[K, V] the type it is checked against asks for
group_by(f), partition(p), associate(f), associate_by(f) a map or a pair of lists

Consumers take the pipeline by value: summing it does not use up the binding, and summing it again runs the stages again from the list. Each element goes through every stage before the next element starts, so a lambda that prints prints in that order. collect() builds whatever it is asked for:

fn main() void {
    readings := [12, 7, 40, 3, 25, 61, 8]

    loud := readings.filter(v => v > 10).map(v => v * 2)
    println("total ${loud.sum()}")
    kept: []int = loud.collect()
    println("kept ${kept}")
    seen: Set[int] = readings.map(v => v % 3).collect()
    println("${seen.len()} remainders")
}

A pipeline consumed where it is written, or bound to a name and consumed later, compiles to one loop over the list with each lambda spliced in place. Each element is lent for its turn, as a for loop over a list lends it, so a string or a struct costs no count unless the pipeline keeps it. A flat_map or flatten over a list of lists is a loop inside that loop, so rows.flat_map { r => r.filter(p).collect() } builds no list per row, and join_of writes each element’s text straight into the joined string. A pipeline handed to another function, stored, or built from a source that is not a list runs through the adapters’ next().

An iterator is not a list. .len(), [i], a list-only method, or passing one where a []T is wanted is an error that says so and suggests the fix — .collect() where the pipeline is made — and atoll check --fix applies it. What needs every element at once stays on lists and answers lists: sorted, sorted_by, shuffled, take_last, skip_last, windowed, chunked, plus, minus, union, intersect and subtract. When the source is long and you only want a prefix, put take first so the later stages see fewer elements.

An iterator ends when its list changes

An iterator borrows what it was made from, as a view of a list does, and so does a pipeline built on one. A change to the list ends the borrow, and a use of the iterator past it is refused (ATOLL1097):

fn main() void {
    mut xs: []int = [1, 2, 3]
    big := xs.filter(v => v > 1)
    xs.push(4)                  // the borrow ends here
    println("${big.sum()}")     // refused: a use past the change
}

What is refused is the use, not the iterator: one you have finished with costs nothing. To keep what it walks past a change, .collect() it first, or make the iterator again after the change. A for over the list is the same borrow, so a change its walk goes on past is refused (ATOLL3105).

Implementing Iterator

Implement next on a struct that holds the traversal state. The struct is the cursor, so next takes &mut self.

struct Countdown { remaining int }

impl Iterator[int] for Countdown {
    fn next(&mut self) Option[int] {
        if self.remaining <= 0 { return None }
        self.remaining = self.remaining - 1
        return Some(self.remaining)
    }
}

fn main() void {
    mut c := Countdown { remaining: 5 }
    for v in c {
        println("${v}")
    }

    // The same traversal without the loop sugar.
    mut d := Countdown { remaining: 3 }
    mut done := false
    for !done {
        match d.next() {
            Some(v) => println("manual ${v}")
            None => { done = true }
        }
    }
}

An iterator does not have to be finite — next may never return None. Bound it where you consume it:

struct Fib { a int, b int }

impl Iterator[int] for Fib {
    fn next(&mut self) Option[int] {
        current := self.a
        self.a = self.b
        self.b = current + self.b
        return Some(current)   // never None
    }
}

fn main() void {
    mut f := Fib { a: 0, b: 1 }
    mut taken: []int = []
    mut done := false
    for !done {
        if taken.len() >= 10 {
            done = true
        } else {
            match f.next() {
                Some(v) => { taken.push(v) }
                None => { done = true }
            }
        }
    }
    for v in taken { println("${v}") }
}

The Iterator default methods (count, find, any, last, …) are declared for every implementor, a user type’s included, and an implementation may override any of them. A consumer walks to the end, so an endless iterator is bounded first: Fib { a: 0, b: 1 }.take(10).collect() is the ten numbers the loop above takes.

Implementing Iterable

Pair the cursor with a collection type that knows how to build one. The associated type Iter names the cursor struct.

struct RingIter { values []int, at int, remaining int, start int }

impl Iterator[int] for RingIter {
    fn next(&mut self) Option[int] {
        if self.remaining <= 0 { return None }
        slot := (self.start + self.at) % self.values.len()
        self.at = self.at + 1
        self.remaining = self.remaining - 1
        return self.values.get(slot.to_usize())
    }
}

struct Ring { values []int, start int }

impl Iterable[int] for Ring {
    type Iter = RingIter

    fn iterator(&self) RingIter {
        return RingIter {
            values:    self.values.clone()
            at:        0
            remaining: self.values.len()
            start:     self.start
        }
    }
}

fn main() void {
    ring := Ring { values: [10, 20, 30, 40], start: 2 }

    // A fresh cursor per traversal, so the ring can be walked repeatedly.
    for v in ring { println("${v}") }
    for v in ring { println("again ${v}") }
}

The rule to follow: iterator() must construct progress state, never hand out a cursor that the collection itself keeps mutating. Returning a shared cursor makes the second traversal silently empty.

Iterable also declares three eager defaults — for_each_item(f), count_items(), and first_item(). As with the Iterator defaults, they are not available to user types yet: ring.count_items() type-checks and then fails to build. A for loop over the source does the same job, and takes its own fresh cursor each time:

struct RingIter { values []int, at int }

impl Iterator[int] for RingIter {
    fn next(&mut self) Option[int] {
        if self.at >= self.values.len() { return None }
        v := self.values.get(self.at.to_usize())
        self.at = self.at + 1
        return v
    }
}

struct Ring { values []int }

impl Iterable[int] for Ring {
    type Iter = RingIter
    fn iterator(&self) RingIter { return RingIter { values: self.values.clone(), at: 0 } }
}

fn count_of(ring &Ring) int {
    mut n := 0
    for _ in ring { n = n + 1 }
    return n
}

fn main() void {
    ring := Ring { values: [1, 2, 3] }

    println("${count_of(ring)}")
    println("${count_of(ring)}")   // still 3 — nothing was consumed
}

Writing generic code

Take I: Iterable[T] when the function traverses a source, and I: Iterator[T] when it drives a cursor it is allowed to consume.

struct Countdown { remaining int }

impl Iterator[int] for Countdown {
    fn next(&mut self) Option[int] {
        if self.remaining <= 0 { return None }
        self.remaining = self.remaining - 1
        return Some(self.remaining)
    }
}

struct Ring { values []int }

impl Iterable[int] for Ring {
    type Iter = Countdown
    fn iterator(&self) Countdown { return Countdown { remaining: self.values.len() } }
}

fn total[I: Iterable[int]](source I) int {
    mut sum := 0
    for v in source { sum = sum + v }
    return sum
}

fn drain[I: Iterator[int]](cursor &mut I) int {
    mut sum := 0
    mut done := false
    for !done {
        match cursor.next() {
            Some(v) => { sum = sum + v }
            None => { done = true }
        }
    }
    return sum
}

fn main() void {
    println("${total(Ring { values: [1, 2, 3, 4] })}")
    mut c := Countdown { remaining: 4 }
    println("${drain(&mut c)}")
}

One sharp edge: those bounds resolve for user types, but a builtin container passed at an Iterable/Iterator bound currently fails monomorphization (type List[?2] does not implement trait Iterable). Take a concrete []T or [..]T parameter when the caller will pass a stdlib collection:

fn total(values []int) int {
    mut sum := 0
    for v in values { sum = sum + v }
    return sum
}

fn main() void {
    println("${total([1, 2, 3, 4])}")
}

That is usually the better signature anyway: []T also gives the algorithm a length and indices, which Iterable does not.

Sources in the stdlib

Every builtin container is iterable, and each yields a different element shape.

fn main() void {
    // List: elements.
    for v in [1, 2, 3] { println("${v}") }

    // String: characters.
    for ch in "abc" { println("${ch}") }

    // Range: half-open, then inclusive.
    for i in 0..3 { println("${i}") }
    for i in 0..=3 { println("${i}") }

    // Set: members, in unspecified order.
    mut tags: Set[string] = Set.new()
    tags.put("x")
    for tag in tags { println(tag) }

    // Map: (K, V) entries, destructured by the loop pattern.
    mut ports: Map[string, int] = Map.new()
    ports.put("http", 80)
    for name, port in ports { println("${name} ${port}") }
}

Indexed traversal is available where positions exist, and enumerate() pairs each element with its index:

fn main() void {
    values := [10, 20, 30]

    for index, value in values.enumerate() {
        println("${index}: ${value}")
    }

    for index in 0..values.len() {
        println("${values.get(index.to_usize()) ?? 0}")
    }

    for value in values.reversed() {
        println("${value}")
    }
}

Prefer direct iteration; reach for an index range only when the index is part of the computation.

A closure takes a pair apart the same way: one of two parameters where a stage hands it a pair binds each to its half, as Rust’s |(i, x)| does.

fn main() int {
    values := [10, 20, 30]
    return values.enumerate().map((i, v) => i.to_int() * v).fold(0, (acc, x) => acc + x)
}

A range of integers is itself an iterator, so every stage applies to it and the pipeline compiles to the counted loop you would write. len() and is_empty() say how many values it holds:

fn main() int {
    squares := (1..=4).map(i => i * i).collect()
    evens := (0..10).filter(i => i % 2 == 0).count()
    return squares[3] + evens + (2..7).len() + if (5..5).is_empty() { 4 } else { 0 }
}

A slice is iterable too, and iterating it borrows rather than copies:

fn main() void {
    values := [1, 2, 3, 4, 5]

    match values.get(1..4) {
        Some(window) => {
            for v in window { println("${v}") }
        }
        None => println("out of range")
    }
}

A Stream is drained with the pattern-consume form rather than for … in:

import task

fn main() void {
    s := task.Stream.new[int](4)
    s.send(1)
    s.send(2)
    s.close()

    for Some(value) := s.recv() {
        println("${value}")
    }
}

A worked example

A log scanner: a custom cursor over records, an Iterable wrapper so the log can be walked more than once, and two consumers — one that stops early, one that visits everything.

struct Record { level string, message string }

struct RecordIter { source []Record, at int }

impl Iterator[Record] for RecordIter {
    fn next(&mut self) Option[Record] {
        if self.at >= self.source.len() { return None }
        item := self.source.get(self.at.to_usize()).cloned()
        self.at = self.at + 1
        return item
    }
}

struct Log { records []Record }

impl Iterable[Record] for Log {
    type Iter = RecordIter
    fn iterator(&self) RecordIter { return RecordIter { source: self.records.clone(), at: 0 } }
}

// Stops pulling as soon as `limit` matches are in hand — the tail of the
// log is never touched.
fn first_errors(log &Log, limit int) []string {
    mut out: []string = []
    mut cursor := log.iterator()
    mut done := false
    for !done {
        if out.len() >= limit {
            done = true
        } else {
            match cursor.next() {
                None => { done = true }
                Some(r) => {
                    if r.level == "error" { out.push(r.message) }
                }
            }
        }
    }
    return out
}

// Takes its own fresh cursor via the `Iterable` impl.
fn counts_by_level(log &Log) Map[string, int] {
    mut counts: Map[string, int] = Map.new()
    for record in log {
        counts.update(record.level, 0, n => n + 1)
    }
    return counts
}

fn main() void {
    log := Log {
        records: [
            Record { level: "info", message: "listening" },
            Record { level: "error", message: "connect refused" },
            Record { level: "warn", message: "slow query" },
            Record { level: "error", message: "timeout" },
            Record { level: "error", message: "disk full" }
        ]
    }

    for message in first_errors(log, 2) {
        println("error: ${message}")
    }

    counts := counts_by_level(log)
    for level in counts.items().sorted() {
        println("${level}: ${counts.get_or_default(level, 0)}")
    }
}

Both functions run against the same Log value, because each one asks the Iterable for its own cursor rather than sharing one.

Type to search…

↑↓ navigate↵ selectEsc close