-
-
Save lloydmeta/f37c192c32f04ef59a9262ef42334d2f 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
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