Skip to content

Commit c21db3b

Browse files
committed
core: Add iter::min/max
1 parent 4eeb706 commit c21db3b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/libcore/iter.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,29 @@ fn repeat(times: uint, blk: fn()) {
8585
}
8686
}
8787

88+
fn min<A:copy,IA:iterable<A>>(self: IA) -> A {
89+
alt foldl(self, none) {|a, b|
90+
alt a {
91+
some(a) { some(math::min(a, b)) }
92+
none { some(b) }
93+
}
94+
} {
95+
some(val) { val }
96+
none { fail "min called on empty iterator" }
97+
}
98+
}
99+
100+
fn max<A:copy,IA:iterable<A>>(self: IA) -> A {
101+
alt foldl(self, none) {|a, b|
102+
alt a {
103+
some(a) { some(math::max(a, b)) }
104+
none { some(b) }
105+
}
106+
} {
107+
some(val) { val }
108+
none { fail "max called on empty iterator" }
109+
}
110+
}
88111

89112
#[test]
90113
fn test_enumerate() {
@@ -168,4 +191,26 @@ fn test_repeat() {
168191
assert c == [0u, 1u, 4u, 9u, 16u];
169192
}
170193

194+
#[test]
195+
fn test_min() {
196+
assert min([5, 4, 1, 2, 3]) == 1;
197+
}
171198

199+
#[test]
200+
#[should_fail]
201+
#[ignore(cfg(target_os = "win32"))]
202+
fn test_min_empty() {
203+
min::<int, [int]>([]);
204+
}
205+
206+
#[test]
207+
fn test_max() {
208+
assert max([1, 2, 4, 2, 3]) == 4;
209+
}
210+
211+
#[test]
212+
#[should_fail]
213+
#[ignore(cfg(target_os = "win32"))]
214+
fn test_max_empty() {
215+
max::<int, [int]>([]);
216+
}

0 commit comments

Comments
 (0)