Created
November 29, 2018 01:15
-
-
Save Fiona-J-W/af04d31ed4a19384e788ed22fdd2a467 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::error::Error; | |
pub trait ResultIterator { | |
type ValueType; | |
type ErrorType; | |
fn fold_results<Acc, Fun>(self, init: Acc, fun: Fun) -> Result<Acc, Self::ErrorType> | |
where | |
Fun: Fn(Acc, &Self::ValueType) -> Acc; | |
} | |
impl<It, V, E> ResultIterator for It | |
where | |
It: Iterator<Item = Result<V, E>>, | |
{ | |
type ValueType = V; | |
type ErrorType = E; | |
fn fold_results<Acc, Fun>(self, init: Acc, fun: Fun) -> Result<Acc, Self::ErrorType> | |
where | |
Fun: Fn(Acc, &Self::ValueType) -> Acc, | |
{ | |
let mut acc = init; | |
for item in self { | |
match item { | |
Ok(x) => acc = fun(acc, &x), | |
Err(e) => return Err(e), | |
} | |
} | |
Ok(acc) | |
} | |
} | |
#[test] | |
fn test_add() -> Result<(), Box<Error>> { | |
assert_eq!( | |
vec!["1", "2", "3"] | |
.iter() | |
.map(|i| i.parse::<f64>()) | |
.fold_results(0.0, |a, b| a + b)?, | |
6.0 | |
); | |
assert!( | |
vec!["one", "2", "3"] | |
.iter() | |
.map(|i| i.parse::<f64>()) | |
.fold_results(0.0, |a, b| a + b) | |
.is_err() | |
); | |
let data: Vec<Result<f64, Box<Error>>> = vec![Ok(1.0), Ok(2.0), Ok(3.0)]; | |
let iter = data.iter(); | |
assert_eq!(iter.fold_results(0.0, |x, y| x + y)?, 6.0); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Errors: