From a59a25d8e64deead0721b6e537a29f600227718f Mon Sep 17 00:00:00 2001 From: Ulrik Sverdrup Date: Mon, 18 Sep 2017 21:27:19 +0200 Subject: [PATCH] core: Implement rfold for Map, Cloned, Chain --- src/libcore/iter/mod.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/libcore/iter/mod.rs b/src/libcore/iter/mod.rs index 65cd28b499e..cee345d52ca 100644 --- a/src/libcore/iter/mod.rs +++ b/src/libcore/iter/mod.rs @@ -461,6 +461,12 @@ impl<'a, I, T: 'a> DoubleEndedIterator for Cloned fn next_back(&mut self) -> Option { self.it.next_back().cloned() } + + fn rfold(self, init: Acc, mut f: F) -> Acc + where F: FnMut(Acc, Self::Item) -> Acc, + { + self.it.rfold(init, move |acc, elt| f(acc, elt.clone())) + } } #[stable(feature = "iter_cloned", since = "1.1.0")] @@ -773,6 +779,26 @@ impl DoubleEndedIterator for Chain where ChainState::Back => self.b.next_back(), } } + + fn rfold(self, init: Acc, mut f: F) -> Acc + where F: FnMut(Acc, Self::Item) -> Acc, + { + let mut accum = init; + match self.state { + ChainState::Both | ChainState::Back => { + accum = self.b.rfold(accum, &mut f); + } + _ => { } + } + match self.state { + ChainState::Both | ChainState::Front => { + accum = self.a.rfold(accum, &mut f); + } + _ => { } + } + accum + } + } // Note: *both* must be fused to handle double-ended iterators. @@ -1106,6 +1132,13 @@ impl DoubleEndedIterator for Map where fn next_back(&mut self) -> Option { self.iter.next_back().map(&mut self.f) } + + fn rfold(self, init: Acc, mut g: G) -> Acc + where G: FnMut(Acc, Self::Item) -> Acc, + { + let mut f = self.f; + self.iter.rfold(init, move |acc, elt| g(acc, f(elt))) + } } #[stable(feature = "rust1", since = "1.0.0")]