x-lang

← Index

x/type/iter

Iterator protocol as the Iter class: build/new/make, drive next/empty?, consume ->list/for-each/fold.

(Iter new seq) iterates lists, vectors, strings, and def-class instances

(instances yield (name . value) pairs); empty sequences give an empty iterator.

Class Iter

(Iter %check it what)

(Iter make step state)

Build an iterator from a pure step function and its starting state – the from-scratch constructor; (Iter new) is the from-a-sequence door. Exhaustion rides the STATE: the step signals the last element by returning a nil next-state (the list step below is the model).

Block form: (Iter make (x) body … state) – or (i x) for the 0-based index, then the element.

Parameters:

Returns: ITER — A fresh iterator

Examples:

(Iter ->list (Iter make (fn (_ st) (if (null? st) () (pair (first st) (rest st)))) (list 1 2 3))) => (1 2 3)

(Iter next it)

The next element, ADVANCING the iterator in place (the C driver writes the successor state back into the box); () once exhausted. (Iter step) is the functional sibling that leaves it untouched.

Parameters:

Returns: ANY — The next element, or nil when exhausted

(Iter step it)

Step ITERATOR functionally: (value . next-iterator) leaving it untouched, or () when exhausted – the generator view of an iterator.

Parameters:

Returns: ANY — Pair of value and successor iterator, or nil

(Iter empty? it)

Is the iterator exhausted? True once next would return nil; the source is not advanced.

Parameters:

Returns: BOOL — True when nothing remains

(Iter iter? x)

Test whether a value is an iterator.

Parameters:

Returns: BOOL — True if x is an iterator

(Iter new x)

An iterator over a sequence, via the type’s iter slot. Instances yield their members as (name . value) pairs; also available bare as iter. Raises type on a value whose type carries no iter slot – an INT, a fn, or one of the engine’s C-built spines such as the reader’s type alist, which are walked with the bare first/rest accessors instead.

Parameters:

Returns: ITER — An iterator positioned at the first element

Examples:

(Iter ->list (Iter new (list 1 2))) => (1 2)

(Iter ->list it)

Drain the iterator into a list, in order; the iterator ends exhausted.

Parameters:

Returns: LIST — Every remaining element

Examples:

(Iter ->list (Iter new "ab")) => (#\a #\b)

(Iter for-each f it)

Drain the iterator applying f to each element for effect; returns nil.

Block form: (Iter for-each (x) body … it) – or (i x) for the 0-based index, then the element.

Parameters:

Returns: ANY — nil

(Iter fold f acc it)

Drain the iterator folding f over the elements, left to right.

Block form: (Iter fold (acc x) body … acc it) – or (acc i x) with the 0-based index ahead of the element.

Parameters:

Returns: ANY — The final accumulator

Examples:

(Iter fold + 0 (Iter new (list 1 2 3))) => 6

iter