From 3edad3555e1f5c01572f32e84480383c1ae2b472 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 12 Feb 2012 02:50:37 -0800 Subject: [PATCH] core: Add iter::count --- src/libcore/iter.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 8500ce7a783..6af10bd8a35 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -82,6 +82,16 @@ fn reverse>(self: IA, blk: fn(A)) { vec::riter(to_list(self), blk) } +fn count>(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 { @@ -223,4 +233,9 @@ fn test_max_empty() { #[test] 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; } \ No newline at end of file