Logo

Programming-Idioms

History of Idiom 247 > diff from v15 to v16

Edit summary for version 16 by Zs:
New Rust implementation by user [Zs]

Version 15

2021-01-23, 23:43:06

Version 16

2021-02-21, 12:56:01

Idiom #247 Filter list in-place

Remove all the elements from list x that don't satisfy the predicate p, without allocating a new list.
Keep all the elements that do satisfy p.

For languages that don't have mutable lists, refer to idiom #57 instead.

Idiom #247 Filter list in-place

Remove all the elements from list x that don't satisfy the predicate p, without allocating a new list.
Keep all the elements that do satisfy p.

For languages that don't have mutable lists, refer to idiom #57 instead.

Variables
x,p
Variables
x,p
Extra Keywords
keep conserve preserve mutable
Extra Keywords
keep conserve preserve mutable
Code
let mut j = 0;
for i in 0..x.len() {
    if p(x[i]) {
        x[j] = x[i];
        j += 1;
    }
}
x.truncate(j);
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8f7530595e213b725e5a3b00d4fbbe74