@@ -41,6 +41,8 @@ much easier to implement.
41
41
42
42
*/
43
43
44
+ use option:: { Option , Some , None } ;
45
+
44
46
pub trait Times {
45
47
fn times ( & self , it : & fn ( ) -> bool ) ;
46
48
}
@@ -104,6 +106,27 @@ pub fn all<T>(predicate: &fn(T) -> bool, iter: &fn(f: &fn(T) -> bool)) -> bool {
104
106
true
105
107
}
106
108
109
+ /**
110
+ * Return the first element where `predicate` returns `true`, otherwise return `Npne` if no element
111
+ * is found.
112
+ *
113
+ * # Example:
114
+ *
115
+ * ~~~~
116
+ * let xs = ~[1u, 2, 3, 4, 5, 6];
117
+ * assert_eq!(*find(|& &x: & &uint| x > 3, |f| xs.each(f)).unwrap(), 4);
118
+ * ~~~~
119
+ */
120
+ #[ inline( always) ]
121
+ pub fn find < T > ( predicate : & fn ( & T ) -> bool , iter : & fn ( f : & fn ( T ) -> bool ) ) -> Option < T > {
122
+ for iter |x| {
123
+ if predicate ( & x) {
124
+ return Some ( x) ;
125
+ }
126
+ }
127
+ None
128
+ }
129
+
107
130
#[ cfg( test) ]
108
131
mod tests {
109
132
use super :: * ;
@@ -128,4 +151,10 @@ mod tests {
128
151
assert ! ( all( |x: uint| x < 6 , |f| uint:: range( 1 , 6 , f) ) ) ;
129
152
assert ! ( !all( |x: uint| x < 5 , |f| uint:: range( 1 , 6 , f) ) ) ;
130
153
}
154
+
155
+ #[ test]
156
+ fn test_find ( ) {
157
+ let xs = ~[ 1 u, 2 , 3 , 4 , 5 , 6 ] ;
158
+ assert_eq ! ( * find( |& & x: & & uint| x > 3 , |f| xs. each( f) ) . unwrap( ) , 4 ) ;
159
+ }
131
160
}
0 commit comments