Skip to content

Commit

Permalink
Add try_product and try_sum
Browse files Browse the repository at this point in the history
`.try_product()` is a more convenient way of writing `.product::<Result<_, _>>()`
`.try_sum()` is a more convenient way of writing `.sum::<Result<_, _>>()`
  • Loading branch information
sjackman committed Dec 7, 2023
1 parent b07b0ad commit 22a1c74
Showing 1 changed file with 47 additions and 6 deletions.
53 changes: 47 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@ extern crate alloc;

#[cfg(feature = "use_alloc")]
use alloc::{string::String, vec::Vec};

pub use either::Either;

use core::borrow::Borrow;
pub use either::Either;
use std::cmp::Ordering;
#[cfg(feature = "use_std")]
use std::collections::HashMap;
Expand Down Expand Up @@ -144,8 +142,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;
Expand Down Expand Up @@ -2195,7 +2192,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::<Result<_, _>>()`
///
/// # Example
Expand Down Expand Up @@ -2223,6 +2220,50 @@ pub trait Itertools: Iterator {
self.collect()
}

/// `.try_product()` is a more convenient way of writing `.product::<Result<_, _>>()`
///
/// # 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<T, U, E>(self) -> Result<U, E>
where
Self: Sized + Iterator<Item = Result<T, E>>,
Result<U, E>: std::iter::Product<Result<T, E>>,
{
self.product()
}

/// `.try_sum()` is a more convenient way of writing `.sum::<Result<_, _>>()`
///
/// # 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<T, U, E>(self) -> Result<U, E>
where
Self: Sized + Iterator<Item = Result<T, E>>,
Result<U, E>: std::iter::Sum<Result<T, E>>,
{
self.sum()
}

/// Assign to each reference in `self` from the `from` iterator,
/// stopping at the shortest of the two iterators.
///
Expand Down

0 comments on commit 22a1c74

Please sign in to comment.