Grav v1.14.0

iter

import "std/core" (included in import "std") · namespace std.core

Iterator<T> gives values one at a time; Iterable<T> is anything that can make a fresh Iterator<T>. A for (x in v) loop walks either: an iterator by calling hasNext() and next(), an iterable by first calling iterator(). The loop only needs those methods, so implementing the interfaces is optional; they are there so a function can take "anything that can be walked".

The standard collections without positions are iterable: LinkedList<T> and HashSet<T> give their elements; HashMap<K, V>, Map<K, V> and SortedMap<K, V> give their entries as Entry<K, V> (a value with first = key and second = value, so walking a map allocates nothing), and a loop can take them apart.

grav
import "std"

// The words of a text, one at a time, made as they are asked for.
class Words implements Iterator<string> {
    private text: string
    private at: int = 0
    constructor(text: string) { self.text = text }
    fn hasNext() -> bool { return self.at < Str.length(self.text) }
    fn next() -> string {
        let end = Str.indexFrom(self.text, " ", self.at)
        if (end < 0) { end = Str.length(self.text) }
        let w = Str.slice(self.text, self.at, end)
        self.at = end + 1
        return w
    }
}

fn main() {
    for (i, w in new Words("to be or")) { print("${i}: ${w}") }

    let ages = new SortedMap<string, int>(fn(a, b) => Str.compare(a, b))
    ages.put("grace", 85)
    ages.put("ada", 36)
    for ((name, age) in ages) { print("${name} is ${age}") }
}
Output
0: to
1: be
2: or
ada is 36
grace is 85

Adding to or removing from a collection while a loop walks it is allowed but may skip or repeat elements; collect the changes and make them afterwards.

API

interface Iterator<T>

Gives values one at a time: next() only after hasNext() said true.

Methods

  • fn hasNext() -> bool — Whether next() has another value.
  • fn next() -> T — The next value.

interface Iterable<T>

Something that can be walked: each call to iterator() starts again from the first value.

Methods

  • fn iterator() -> Iterator<T> — A new iterator over the values.

Edit this page on GitHub