Main module with utility functions for working efficiently with iterators.
See the Iter module from the base lib for more information on the Iter type.
To get started, you'll need to import the Iter module from both the base library and this one.
import Iter "mo:base/Iter";
import Itertools "mo:itertools/Iter";
Converting data types to iterators is the next step.
[1, 2, 3, 4, 5].vals()Iter.fromArray([1, 2, 3, 4, 5])Iter.fromList(list)"Hello, world!".chars()Text.split("a,b,c", #char ',')Buffer.toArray(buffer).vals()map.entries()For conversion of other data types to iterators, you can look in the base library for the specific data type's documentation.
Here are some examples of using the functions in this library to create simple and efficient iterators for solving different problems:
range and sum to find the sum of values from 1 to 25: let range = Itertools.range(1, 25 + 1);
let sum = Itertools.sum(range, Nat.add);
assert sum == ?325;
let vals = [1, 2, 3, 4, 5, 6].vals();
let iterWithIndices = Itertools.enumerate(vals);
let isEven = func ( x : (Int, Int)) : Bool { x.1 % 2 == 0 };
let mapIndex = func (x : (Int, Int)) : Int { x.0 };
let evenIndices = Itertools.mapFilter(iterWithIndices, isEven, mapIndex);
assert Iter.toArray(evenIndices) == [1, 3, 5];
let vals = [5, 3, 3, 7, 8, 10].vals();
let tuples = Itertools.slidingTuples(vals);
// Iter.toArray(tuples) == [(5, 3), (3, 3), (3, 7), (7, 8), (8, 10)]
let diff = func (x : (Int, Int)) : Int { x.1 - x.0 };
let iter = Iter.map(tuples, diff);
assert Iter.toArray(iter) == [-2, 0, 4, 1, 2];Peekable Iterator
An iterator equipped with a peek method that returns the next value without advancing the iterator.
The PeekableIter type is an extension of the Iter type built in Motoko
so it is compatible with all the function defined for the Iter type.
Reversible Iterator
This type of iterator allows for both forward and backward iteration Reversible Iterators are useful for iterating over data structures in reverse without allocating extra space for the reverse iteration.
The
RevItertype is an extension of theItertype built in Motoko so it is compatible with all the function defined for theItertype.The
RevIteris intended to be used with functions for theItertype to avoid rewriting similar functions for both types.n: