Skip to content

Commit

Permalink
Added filtered method for Option type
Browse files Browse the repository at this point in the history
  • Loading branch information
hanny24 committed Jun 21, 2013
1 parent d1927d2 commit f3966e4
Showing 1 changed file with 17 additions and 0 deletions.
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());
}

5 comments on commit f3966e4

@bors
Copy link
Contributor

@bors bors commented on f3966e4 Jun 24, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from msullivan
at hanny24@f3966e4

@bors
Copy link
Contributor

@bors bors commented on f3966e4 Jun 24, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging hanny24/rust/master = f3966e4 into auto

@bors
Copy link
Contributor

@bors bors commented on f3966e4 Jun 24, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hanny24/rust/master = f3966e4 merged ok, testing candidate = ac4211e

@bors
Copy link
Contributor

@bors bors commented on f3966e4 Jun 24, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = ac4211e

Please sign in to comment.