Skip to content

Commit a6eaa3b

Browse files
committed
iter: add max and min functions
1 parent 6f18bb5 commit a6eaa3b

File tree

1 file changed

+66
-2
lines changed

1 file changed

+66
-2
lines changed

src/libcore/iter.rs

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ much easier to implement.
4141
4242
*/
4343

44+
use cmp::Ord;
4445
use option::{Option, Some, None};
4546

4647
pub trait Times {
@@ -107,8 +108,7 @@ pub fn all<T>(predicate: &fn(T) -> bool, iter: &fn(f: &fn(T) -> bool)) -> bool {
107108
}
108109

109110
/**
110-
* Return the first element where `predicate` returns `true`, otherwise return `Npne` if no element
111-
* is found.
111+
* Return the first element where `predicate` returns `true`. Return `None` if no element is found.
112112
*
113113
* # Example:
114114
*
@@ -127,6 +127,58 @@ pub fn find<T>(predicate: &fn(&T) -> bool, iter: &fn(f: &fn(T) -> bool)) -> Opti
127127
None
128128
}
129129

130+
/**
131+
* Return the largest item yielded by an iterator. Return `None` if the iterator is empty.
132+
*
133+
* # Example:
134+
*
135+
* ~~~~
136+
* let xs = ~[8, 2, 3, 1, -5, 9, 11, 15];
137+
* assert_eq!(max(|f| xs.each(f)).unwrap(), &15);
138+
* ~~~~
139+
*/
140+
#[inline]
141+
pub fn max<T: Ord>(iter: &fn(f: &fn(T) -> bool)) -> Option<T> {
142+
let mut result = None;
143+
for iter |x| {
144+
match result {
145+
Some(ref mut y) => {
146+
if x > *y {
147+
*y = x;
148+
}
149+
}
150+
None => result = Some(x)
151+
}
152+
}
153+
result
154+
}
155+
156+
/**
157+
* Return the smallest item yielded by an iterator. Return `None` if the iterator is empty.
158+
*
159+
* # Example:
160+
*
161+
* ~~~~
162+
* let xs = ~[8, 2, 3, 1, -5, 9, 11, 15];
163+
* assert_eq!(max(|f| xs.each(f)).unwrap(), &-5);
164+
* ~~~~
165+
*/
166+
#[inline]
167+
pub fn min<T: Ord>(iter: &fn(f: &fn(T) -> bool)) -> Option<T> {
168+
let mut result = None;
169+
for iter |x| {
170+
match result {
171+
Some(ref mut y) => {
172+
if x < *y {
173+
*y = x;
174+
}
175+
}
176+
None => result = Some(x)
177+
}
178+
}
179+
result
180+
}
181+
130182
#[cfg(test)]
131183
mod tests {
132184
use super::*;
@@ -157,4 +209,16 @@ mod tests {
157209
let xs = ~[1u, 2, 3, 4, 5, 6];
158210
assert_eq!(*find(|& &x: & &uint| x > 3, |f| xs.each(f)).unwrap(), 4);
159211
}
212+
213+
#[test]
214+
fn test_max() {
215+
let xs = ~[8, 2, 3, 1, -5, 9, 11, 15];
216+
assert_eq!(max(|f| xs.each(f)).unwrap(), &15);
217+
}
218+
219+
#[test]
220+
fn test_min() {
221+
let xs = ~[8, 2, 3, 1, -5, 9, 11, 15];
222+
assert_eq!(min(|f| xs.each(f)).unwrap(), &-5);
223+
}
160224
}

0 commit comments

Comments
 (0)