From a369c6a996dcc28d52868c3c118ca4b686c026f8 Mon Sep 17 00:00:00 2001 From: Shaun Jackman Date: Thu, 7 Dec 2023 12:11:30 -0800 Subject: [PATCH] Add `try_product` and `try_sum` `.try_product()` is a more convenient way of writing `.product::>()` `.try_sum()` is a more convenient way of writing `.sum::>()` --- src/lib.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index bdb436e48..b1d2dfe94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -144,8 +144,7 @@ pub mod traits { pub use crate::concat_impl::concat; pub use crate::cons_tuples_impl::cons_tuples; -pub use crate::diff::diff_with; -pub use crate::diff::Diff; +pub use crate::diff::{diff_with, Diff}; #[cfg(feature = "use_alloc")] pub use crate::kmerge_impl::kmerge_by; pub use crate::minmax::MinMaxResult; @@ -2195,7 +2194,7 @@ pub trait Itertools: Iterator { self.collect() } - /// `.try_collect()` is more convenient way of writing + /// `.try_collect()` is a more convenient way of writing /// `.collect::>()` /// /// # Example @@ -2223,6 +2222,50 @@ pub trait Itertools: Iterator { self.collect() } + /// `.try_product()` is a more convenient way of writing `.product::>()` + /// + /// # Example + /// + /// ``` + /// use itertools::Itertools; + /// use std::str::FromStr; + /// + /// fn main() -> Result<(), std::num::ParseIntError> { + /// let product: u64 = ["1", "2", "3"].iter().map(|x| u64::from_str(x)).try_product()?; + /// assert_eq!(product, 6); + /// Ok(()) + /// } + /// ``` + fn try_product(self) -> Result + where + Self: Sized + Iterator>, + Result: std::iter::Product>, + { + self.product() + } + + /// `.try_sum()` is a more convenient way of writing `.sum::>()` + /// + /// # Example + /// + /// ``` + /// use itertools::Itertools; + /// use std::str::FromStr; + /// + /// fn main() -> Result<(), std::num::ParseIntError> { + /// let sum: u64 = ["1", "2", "3"].iter().map(|x| u64::from_str(x)).try_sum()?; + /// assert_eq!(sum, 6); + /// Ok(()) + /// } + /// ``` + fn try_sum(self) -> Result + where + Self: Sized + Iterator>, + Result: std::iter::Sum>, + { + self.sum() + } + /// Assign to each reference in `self` from the `from` iterator, /// stopping at the shortest of the two iterators. ///