Range Over Iterators in OpenSCAD

Starting with version 1.23, Go has added support for iterators, which lets us range over pretty much anything!

Let’s look at the List type from the previous example again. In that example, we had an AllElements method that returned a slice of all elements in the list. With Go iterators, we can do it better - as shown below.

module List(T){
    head = undef;
    tail = undef;
}

module element(T){
    next = undef;
    val = T;
}

module Push(lst, v){
    if (lst.tail == undef){
        lst.head = [val=v, next=undef];
        lst.tail = lst.head;
    } else {
        lst.tail[1] = [val=v, next=undef];
        lst.tail = lst.tail[1];
    }
}

module All(lst){
    e = lst.head;
    while (e != undef){
        yield(e.val);
        e = e.next;
    }
}

module genFib(){
    a = 1;
    b = 1;
    while (true){
        yield(a);
        next = a + b;
        a = b;
        b = next;
    }
}

module main(){
    lst = [head=undef, tail=undef];
    Push(lst, 10);
    Push(lst, 13);
    Push(lst, 23);

    for (e = All(lst)){
        echo(e);
    }

    all = All(lst);
    echo(all);

    for (n = genFib()){
        if (n >= 10){
            break;
        }
        echo(n);
    }
}

All returns an iterator, which in Go is a function with a special signature.

The iterator function takes another function as a parameter, called yield by convention (but the name can be arbitrary). It will call yield for every element we want to iterate over and note yield’s return value for a potential early termination.

Iteration doesn’t require an underlying data structure, and doesn’t even have to be finite! Here’s a function returning an iterator over Fibonacci numbers: it keeps running as long as yield keeps returning true.

Since List.All returns an iterator, we can use it in a regular for loop.

Packages like slices have a number of useful functions to work with iterators. For example, Collect takes any iterator and collects all its values into a slice.

Once the loop hits break or an early return, the yield function passed to the iterator will return false.