Last active
September 10, 2017 05:50
-
-
Save xevix/71c0eb0f33ae3720f5e71e7a41edff20 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
trait Folder { | |
type Item; | |
fn foldl1<F>(self, f: F) -> Option<Self::Item> | |
where | |
F: FnMut(Self::Item, &Self::Item) -> Self::Item; | |
} | |
impl<T: Clone> Folder for Vec<T> { | |
type Item = T; | |
fn foldl1<F>(self, mut f: F) -> Option<Self::Item> | |
where | |
F: FnMut(Self::Item, &Self::Item) -> Self::Item | |
{ | |
if let Some(init) = self.first() { | |
let mut accum = (*init).clone(); | |
for x in self[1..].iter() { | |
accum = f(accum, x); | |
} | |
Some(accum) | |
} else { | |
None | |
} | |
} | |
} | |
fn combine_all_optionf<T>(xs: &Vec<T>) -> Option<T> | |
where | |
T: Semigroup + Clone, | |
{ | |
xs.clone().foldl1(|acc, next| acc.combine(next)) | |
} | |
extern crate frunk; | |
use frunk::semigroup::*; | |
fn main() { | |
let vec = vec![1, 2, 3]; | |
println!("Vec: {:?}", vec); | |
let res = combine_all_optionf(&vec); | |
match res { | |
Some(num) => println!("Result is: {}", num), | |
None => println!("Empty vec") | |
} | |
println!("Hello, world!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment