Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions src/Iter.mo
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,40 @@ module {
/// ```
public func map<A, B>(xs : Iter<A>, f : A -> B) : Iter<B> = object {
public func next() : ?B {
label l loop {
switch (xs.next()) {
case (?next) {
?f(next);
};
case (null) {
null;
};
};
};
};

/// 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";
/// let iter = Iter.range(1, 3);
/// let mappedIter = Iter.filter(iter, func (x : Nat) : Bool { x % 2 == 1 });
/// assert(?1 == mappedIter.next());
/// assert(?3 == mappedIter.next());
/// assert(null == mappedIter.next());
/// ```
public func filter<A>(xs : Iter<A>, f : A -> Bool) : Iter<A> = object {
public func next() : ?A {
loop {
switch (xs.next()) {
case (?next) {
return ?f(next);
};
case (null) {
break l;
return null;
};
case (?x) {
if (f(x)) {
return ?x;
};
};
};
continue l;
};
null;
};
Expand Down
16 changes: 16 additions & 0 deletions test/iterTest.mo
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,22 @@ do {
};
};

do {
Debug.print(" filter");

let isOdd = func (x : Int) : Bool {
x % 2 == 1;
};

let _actual = Iter.filter<Nat>([ 1, 2, 3 ].vals(), isOdd);
let actual = [var 0, 0];
Iter.iterate<Nat>(_actual, func (x, i) { actual[i] := x; });

let expected = [1, 3];

assert(actual == expected);
};

do {
Debug.print(" make");

Expand Down