Last active
February 6, 2019 13:17
-
-
Save nyinyithann/09fddc26f46170ddc08f8aabe2641be3 to your computer and use it in GitHub Desktop.
add fold method to Option<T>
This file contains hidden or 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::borrow::BorrowMut; | |
pub trait OptionExt<T> { | |
fn fold<S, F>(&self, state: S, folder: F) -> S | |
where | |
F: FnOnce(S, &T) -> S; | |
} | |
impl<T> OptionExt<T> for Option<T> { | |
fn fold<S, F>(&self, state: S, folder: F) -> S | |
where | |
F: (FnOnce(S, &T) -> S), | |
{ | |
match self { | |
Some(x) => folder(state, &x), | |
None => state, | |
} | |
} | |
} | |
fn main() { | |
let opt = Some(10); | |
let opt_sum = opt.fold(1, |s, x| s + x); | |
println!("opt_sum = {}", opt_sum); | |
let opt_list = Some(1..=10); | |
let opt_list_sum = opt_list.fold(0, |s, x| x.clone().borrow_mut().fold(s, |acc, y| acc + y)); | |
println!("opt_list_sum = {}", opt_list_sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment