Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Last active February 6, 2019 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyinyithann/09fddc26f46170ddc08f8aabe2641be3 to your computer and use it in GitHub Desktop.
Save nyinyithann/09fddc26f46170ddc08f8aabe2641be3 to your computer and use it in GitHub Desktop.
add fold method to Option<T>
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