Skip to content

Instantly share code, notes, and snippets.

@nikomatsakis
Created November 22, 2013 21:50
Show Gist options
  • Save nikomatsakis/7607473 to your computer and use it in GitHub Desktop.
Save nikomatsakis/7607473 to your computer and use it in GitHub Desktop.
fn compact<T>(x: &mut ~[T],
keep: |&T| -> bool) {
if x.len() == 0 {
return;
}
let mut kept = 0;
let mut finger = 0;
let mut last = x.len() - 1;
while finger <= last {
if keep(&x[finger]) {
x.swap(kept, finger);
kept += 1;
}
finger += 1;
}
x.truncate(kept);
}
fn main() {
let mut x: ~[uint] = ~[1, 2, 3, 4, 5, 6];
compact(&mut x, |x| x % 2 == 0);
println!("{:?}", x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment