Skip to content

Commit b4cea35

Browse files
committed
libcore: Add IteratorUtil::fold, count
1 parent 02945f1 commit b4cea35

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libcore/iterator.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ pub trait IteratorUtil<A> {
5050
fn nth(&mut self, n: uint) -> A;
5151
fn first(&mut self) -> A;
5252
fn last(&mut self) -> A;
53+
fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B;
54+
fn count(&mut self) -> uint;
5355
}
5456

5557
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -184,6 +186,23 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
184186
for self.advance |e| { elm = e; }
185187
return elm;
186188
}
189+
190+
/// Reduce an iterator to an accumulated value
191+
#[inline]
192+
fn fold<B>(&mut self, init: B, f: &fn(B, A) -> B) -> B {
193+
let mut accum = init;
194+
loop {
195+
match self.next() {
196+
Some(x) => { accum = f(accum, x); }
197+
None => { break; }
198+
}
199+
}
200+
return accum;
201+
}
202+
203+
/// Count the number of an iterator elemenrs
204+
#[inline(always)]
205+
fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) }
187206
}
188207

189208
pub struct ChainIterator<T, U> {
@@ -648,4 +667,12 @@ mod tests {
648667
let v: &[uint] = &[];
649668
v.iter().last();
650669
}
670+
671+
#[test]
672+
fn test_iterator_count() {
673+
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
674+
assert_eq!(v.slice(0, 4).iter().count(), 4);
675+
assert_eq!(v.slice(0, 10).iter().count(), 10);
676+
assert_eq!(v.slice(0, 0).iter().count(), 0);
677+
}
651678
}

0 commit comments

Comments
 (0)