about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorDaniel Micay <danielmicay@gmail.com>2013-04-30 13:01:20 -0400
committerDaniel Micay <danielmicay@gmail.com>2013-04-30 13:07:14 -0400
commit6f18bb550e1293e77281b1cc76f1830a4da2d355 (patch)
tree33d101fa2b1800070f7d795a6d389c742264f1fc /src/libcore
parent7fed4800733805156f0d157e45b01de405c4b48e (diff)
downloadrust-6f18bb550e1293e77281b1cc76f1830a4da2d355.tar.gz
rust-6f18bb550e1293e77281b1cc76f1830a4da2d355.zip
iter: add a find function
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/iter.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs
index 7476531ef94..6f3c6890228 100644
--- a/src/libcore/iter.rs
+++ b/src/libcore/iter.rs
@@ -41,6 +41,8 @@ much easier to implement.
 
 */
 
+use option::{Option, Some, None};
+
 pub trait Times {
     fn times(&self, it: &fn() -> bool);
 }
@@ -104,6 +106,27 @@ pub fn all<T>(predicate: &fn(T) -> bool, iter: &fn(f: &fn(T) -> bool)) -> bool {
     true
 }
 
+/**
+ * Return the first element where `predicate` returns `true`, otherwise return `Npne` if no element
+ * is found.
+ *
+ * # Example:
+ *
+ * ~~~~
+ * let xs = ~[1u, 2, 3, 4, 5, 6];
+ * assert_eq!(*find(|& &x: & &uint| x > 3, |f| xs.each(f)).unwrap(), 4);
+ * ~~~~
+ */
+#[inline(always)]
+pub fn find<T>(predicate: &fn(&T) -> bool, iter: &fn(f: &fn(T) -> bool)) -> Option<T> {
+    for iter |x| {
+        if predicate(&x) {
+            return Some(x);
+        }
+    }
+    None
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -128,4 +151,10 @@ mod tests {
         assert!(all(|x: uint| x < 6, |f| uint::range(1, 6, f)));
         assert!(!all(|x: uint| x < 5, |f| uint::range(1, 6, f)));
     }
+
+    #[test]
+    fn test_find() {
+        let xs = ~[1u, 2, 3, 4, 5, 6];
+        assert_eq!(*find(|& &x: & &uint| x > 3, |f| xs.each(f)).unwrap(), 4);
+    }
 }