about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBrian Anderson <banderson@mozilla.com>2012-02-12 02:36:40 -0800
committerBrian Anderson <banderson@mozilla.com>2012-02-12 19:24:24 -0800
commitc21db3bbc28c47e846783dedfe1eb1228f955f2b (patch)
tree180fe57534dfe2e2f808a11e7cc65d2f35f808b6
parent4eeb706e84bc9e32aa5057e32d567ccab2c3cc2c (diff)
downloadrust-c21db3bbc28c47e846783dedfe1eb1228f955f2b.tar.gz
rust-c21db3bbc28c47e846783dedfe1eb1228f955f2b.zip
core: Add iter::min/max
-rw-r--r--src/libcore/iter.rs45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs
index 7aa08a6980c..23779e04487 100644
--- a/src/libcore/iter.rs
+++ b/src/libcore/iter.rs
@@ -85,6 +85,29 @@ fn repeat(times: uint, blk: fn()) {
     }
 }
 
+fn min<A:copy,IA:iterable<A>>(self: IA) -> A {
+    alt foldl(self, none) {|a, b|
+        alt a {
+          some(a) { some(math::min(a, b)) }
+          none { some(b) }
+        }
+    } {
+        some(val) { val }
+        none { fail "min called on empty iterator" }
+    }
+}
+
+fn max<A:copy,IA:iterable<A>>(self: IA) -> A {
+    alt foldl(self, none) {|a, b|
+        alt a {
+          some(a) { some(math::max(a, b)) }
+          none { some(b) }
+        }
+    } {
+        some(val) { val }
+        none { fail "max called on empty iterator" }
+    }
+}
 
 #[test]
 fn test_enumerate() {
@@ -168,4 +191,26 @@ fn test_repeat() {
     assert c == [0u, 1u, 4u, 9u, 16u];
 }
 
+#[test]
+fn test_min() {
+    assert min([5, 4, 1, 2, 3]) == 1;
+}
 
+#[test]
+#[should_fail]
+#[ignore(cfg(target_os = "win32"))]
+fn test_min_empty() {
+    min::<int, [int]>([]);
+}
+
+#[test]
+fn test_max() {
+    assert max([1, 2, 4, 2, 3]) == 4;
+}
+
+#[test]
+#[should_fail]
+#[ignore(cfg(target_os = "win32"))]
+fn test_max_empty() {
+    max::<int, [int]>([]);
+}