Created
November 22, 2013 21:50
-
-
Save nikomatsakis/7607473 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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