Skip to content

Commit

Permalink
Add Iter.concat function (#650)
Browse files Browse the repository at this point in the history
this PR adds `Iter.concat` utility function, which concatenates two
iterables.

Additionally fixed compilation warning on unused variable and a typo in
doc string
  • Loading branch information
AndyGura authored Jul 31, 2024
1 parent d703347 commit cf19537
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/Iter.mo
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ module {
/// Takes a function and an iterator and returns a new iterator that produces
/// elements from the original iterator if and only if the predicate is true.
/// ```motoko
/// import Iter "o:base/Iter";
/// import Iter "mo:base/Iter";
/// let iter = Iter.range(1, 3);
/// let mappedIter = Iter.filter(iter, func (x : Nat) : Bool { x % 2 == 1 });
/// assert(?1 == mappedIter.next());
Expand Down Expand Up @@ -153,6 +153,37 @@ module {
}
};

/// Takes two iterators and returns a new iterator that produces
/// elements from the original iterators sequentally.
/// ```motoko
/// import Iter "mo:base/Iter";
/// let iter1 = Iter.range(1, 2);
/// let iter2 = Iter.range(5, 6);
/// let concatenatedIter = Iter.concat(iter1, iter2);
/// assert(?1 == concatenatedIter.next());
/// assert(?2 == concatenatedIter.next());
/// assert(?5 == concatenatedIter.next());
/// assert(?6 == concatenatedIter.next());
/// assert(null == concatenatedIter.next());
/// ```
public func concat<A>(a : Iter<A>, b : Iter<A>) : Iter<A> {
var aEnded : Bool = false;
object {
public func next() : ?A {
if (aEnded) {
return b.next();
};
switch (a.next()) {
case (?x) ?x;
case (null) {
aEnded := true;
b.next();
};
};
};
};
};

/// Creates an iterator that produces the elements of an Array in ascending index order.
/// ```motoko
/// import Iter "mo:base/Iter";
Expand Down Expand Up @@ -196,7 +227,7 @@ module {
/// ```
public func toArray<A>(xs : Iter<A>) : [A] {
let buffer = Buffer.Buffer<A>(8);
iterate(xs, func(x : A, _ix : Nat) { buffer.add(x) });
iterate(xs, func(x : A, _ : Nat) { buffer.add(x) });
return Buffer.toArray(buffer)
};

Expand Down

0 comments on commit cf19537

Please sign in to comment.