core: Add iter::count

This commit is contained in:
Brian Anderson 2012-02-12 02:50:37 -08:00
parent 85175d639f
commit 3edad3555e

View file

@ -82,6 +82,16 @@ fn reverse<A:copy,IA:iterable<A>>(self: IA, blk: fn(A)) {
vec::riter(to_list(self), blk)
}
fn count<A,IA:iterable<A>>(self: IA, x: A) -> uint {
foldl(self, 0u) {|count, value|
if value == x {
count + 1u
} else {
count
}
}
}
fn repeat(times: uint, blk: fn()) {
let i = 0u;
while i < times {
@ -224,3 +234,8 @@ fn test_max_empty() {
fn test_reverse() {
assert to_list(bind reverse([1, 2, 3], _)) == [3, 2, 1];
}
#[test]
fn test_count() {
assert count([1, 2, 1, 2, 1], 1) == 3u;
}