]> git.lizzy.rs Git - rust.git/commitdiff
iter: Implement .fold() for .cloned() and .map()
authorUlrik Sverdrup <bluss@users.noreply.github.com>
Tue, 25 Oct 2016 13:50:52 +0000 (15:50 +0200)
committerUlrik Sverdrup <bluss@users.noreply.github.com>
Tue, 25 Oct 2016 13:50:52 +0000 (15:50 +0200)
Implement .fold() specifically for .map() and .cloned() so that any
inner fold improvements are available through map and cloned.

src/libcore/iter/mod.rs

index 9eeb2608071c2fd4bca9f43479e64b36f861f756..2c3b8864a115e4c7d877d0291f5b8eec5f9c5e32 100644 (file)
@@ -399,6 +399,12 @@ fn next(&mut self) -> Option<T> {
     fn size_hint(&self) -> (usize, Option<usize>) {
         self.it.size_hint()
     }
+
+    fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
+        where F: FnMut(Acc, Self::Item) -> Acc,
+    {
+        self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
+    }
 }
 
 #[stable(feature = "iter_cloned", since = "1.1.0")]
@@ -939,6 +945,13 @@ fn next(&mut self) -> Option<B> {
     fn size_hint(&self) -> (usize, Option<usize>) {
         self.iter.size_hint()
     }
+
+    fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
+        where G: FnMut(Acc, Self::Item) -> Acc,
+    {
+        let mut f = self.f;
+        self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]