Skip to content

Instantly share code, notes, and snippets.

@mo-xiaoming
Created October 31, 2022 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mo-xiaoming/34a4588ebbf3835ca231956a3052da96 to your computer and use it in GitHub Desktop.
Save mo-xiaoming/34a4588ebbf3835ca231956a3052da96 to your computer and use it in GitHub Desktop.
c++ std::adjacent_difference in rust
// https://godbolt.org/z/93EE958vG
struct AdjacentDifference<I, F, R>
where
I: Iterator,
F: Fn(I::Item, I::Item) -> R,
R: From<I::Item>
{
prev: Option<I::Item>,
it: I,
f: F,
}
impl<I, F, R> Iterator for AdjacentDifference<I, F, R>
where
I: Iterator,
I::Item: Copy,
F: Fn(I::Item, I::Item) -> R,
R: From<I::Item>,
{
type Item = R;
fn next(&mut self) -> Option<Self::Item> {
self.it.next().map(|i| {
let r = self.prev.map_or_else(|| i.into(), |p| (self.f)(i, p));
self.prev = Some(i);
r
})
}
}
trait AdjacentDifferenceExt: Iterator
where
Self: Sized,
{
fn adjacent_difference<F, R>(self, f: F) -> AdjacentDifference<Self, F, R>
where
<Self as Iterator>::Item: Copy,
F: Fn(<Self as Iterator>::Item, <Self as Iterator>::Item) -> R,
R: From<<Self as Iterator>::Item>
{
AdjacentDifference {
prev: None,
it: self,
f
}
}
}
impl<I> AdjacentDifferenceExt for I where I: Iterator {}
fn main() {
let v = [1, 7, 3, 5, 7, 2, 1];
for i in v.iter().copied().adjacent_difference(|a, b| a - b) {
println!("{}", i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment