Skip to content

Commit c59f965

Browse files
committed
Add try_product and try_sum
`.try_product()` is a more convenient way of writing `.product::<Result<_, _>>()` `.try_sum()` is a more convenient way of writing `.sum::<Result<_, _>>()`
1 parent 0fc4675 commit c59f965

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

src/lib.rs

+46-3
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,7 @@ pub mod traits {
144144

145145
pub use crate::concat_impl::concat;
146146
pub use crate::cons_tuples_impl::cons_tuples;
147-
pub use crate::diff::diff_with;
148-
pub use crate::diff::Diff;
147+
pub use crate::diff::{diff_with, Diff};
149148
#[cfg(feature = "use_alloc")]
150149
pub use crate::kmerge_impl::kmerge_by;
151150
pub use crate::minmax::MinMaxResult;
@@ -2195,7 +2194,7 @@ pub trait Itertools: Iterator {
21952194
self.collect()
21962195
}
21972196

2198-
/// `.try_collect()` is more convenient way of writing
2197+
/// `.try_collect()` is a more convenient way of writing
21992198
/// `.collect::<Result<_, _>>()`
22002199
///
22012200
/// # Example
@@ -2223,6 +2222,50 @@ pub trait Itertools: Iterator {
22232222
self.collect()
22242223
}
22252224

2225+
/// `.product_ok()` is a more convenient way of writing `.product::<Result<_, _>>()`
2226+
///
2227+
/// # Example
2228+
///
2229+
/// ```
2230+
/// use itertools::Itertools;
2231+
/// use std::str::FromStr;
2232+
///
2233+
/// fn main() -> Result<(), std::num::ParseIntError> {
2234+
/// let product: u64 = ["1", "2", "3"].iter().map(|x| u64::from_str(x)).product_ok()?;
2235+
/// assert_eq!(product, 6);
2236+
/// Ok(())
2237+
/// }
2238+
/// ```
2239+
fn product_ok<T, U, E>(self) -> Result<U, E>
2240+
where
2241+
Self: Sized + Iterator<Item = Result<T, E>>,
2242+
Result<U, E>: std::iter::Product<Result<T, E>>,
2243+
{
2244+
self.product()
2245+
}
2246+
2247+
/// `.sum_ok()` is a more convenient way of writing `.sum::<Result<_, _>>()`
2248+
///
2249+
/// # Example
2250+
///
2251+
/// ```
2252+
/// use itertools::Itertools;
2253+
/// use std::str::FromStr;
2254+
///
2255+
/// fn main() -> Result<(), std::num::ParseIntError> {
2256+
/// let sum: u64 = ["1", "2", "3"].iter().map(|x| u64::from_str(x)).sum_ok()?;
2257+
/// assert_eq!(sum, 6);
2258+
/// Ok(())
2259+
/// }
2260+
/// ```
2261+
fn sum_ok<T, U, E>(self) -> Result<U, E>
2262+
where
2263+
Self: Sized + Iterator<Item = Result<T, E>>,
2264+
Result<U, E>: std::iter::Sum<Result<T, E>>,
2265+
{
2266+
self.sum()
2267+
}
2268+
22262269
/// Assign to each reference in `self` from the `from` iterator,
22272270
/// stopping at the shortest of the two iterators.
22282271
///

0 commit comments

Comments
 (0)