Skip to content

Instantly share code, notes, and snippets.

@lloydmeta
Forked from xevix/loop.rs
Last active September 10, 2017 02:54
Show Gist options
  • Save lloydmeta/f37c192c32f04ef59a9262ef42334d2f to your computer and use it in GitHub Desktop.
Save lloydmeta/f37c192c32f04ef59a9262ef42334d2f to your computer and use it in GitHub Desktop.
pub fn combine_all_option<T>(xs: &Vec<T>) -> Option<T>
where
T: Semigroup + Clone,
{
xs.iter().skip(1).fold(
xs.first().map(|v| v.clone()),
|acc, next| acc.map(|v| v.combine(next)),
)
}
// added a few more tests just because
#[test]
fn test_combine_all_option() {
let v0 = &Vec::<i32>::new();
assert_eq!(combine_all_option(v0), None);
let v1 = &vec![1, 2, 3];
assert_eq!(combine_all_option(v1), Some(6));
let v2 = &vec![Some(1), Some(2), Some(3)];
assert_eq!(combine_all_option(v2), Some(Some(6)));
let v3 = &vec![1];
assert_eq!(combine_all_option(v3), Some(1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment