Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

filtered for Option type #7279

Merged
merged 1 commit into from
Jun 24, 2013
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/libstd/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,15 @@ impl<T> Option<T> {
}
}

/// Filters an optional value using given function.
#[inline(always)]
pub fn filtered<'a>(self, f: &fn(t: &'a T) -> bool) -> Option<T> {
match self {
Some(x) => if(f(&x)) {Some(x)} else {None},
None => None
}
}

/// Maps a `some` value from one type to another by reference
#[inline(always)]
pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
Expand Down Expand Up @@ -459,3 +468,11 @@ fn test_get_or_zero() {
let no_stuff: Option<int> = None;
assert_eq!(no_stuff.get_or_zero(), 0);
}

#[test]
fn test_filtered() {
let some_stuff = Some(42);
let modified_stuff = some_stuff.filtered(|&x| {x < 10});
assert_eq!(some_stuff.get(), 42);
assert!(modified_stuff.is_none());
}