Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trait SliceExt<T> {
- fn split_by<F>(&self, pred: F) -> (&[T], &[T])
- where
- F: FnMut(&T) -> bool;
- }
- impl<T> SliceExt<T> for [T] {
- fn split_by<F>(&self, mut pred: F) -> (&[T], &[T])
- where
- F: FnMut(&T) -> bool,
- {
- let p = self
- .iter()
- .enumerate()
- .find(|&(_, val)| !pred(val))
- .map(|(pos, _)| pos)
- .unwrap_or_else(|| self.len());
- self.split_at(p)
- }
- }
- fn main() {
- assert!([].split_by(|x: &i32| *x < 10) == (&[], &[]));
- assert!([1].split_by(|&x| x < 10) == (&[1], &[]));
- assert!([1, 11].split_by(|&x| x < 10) == (&[1], &[11]));
- assert!([1, 2, 10, 11].split_by(|&x| x < 10) == (&[1, 2], &[10, 11]));
- assert!([11].split_by(|&x| x < 10) == (&[], &[11]));
- }
Add Comment
Please, Sign In to add comment