Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Would filter_position or the like be worth adding? #691

Open
MultisampledNight opened this issue Apr 3, 2023 · 2 comments
Open

Would filter_position or the like be worth adding? #691

MultisampledNight opened this issue Apr 3, 2023 · 2 comments

Comments

@MultisampledNight
Copy link

MultisampledNight commented Apr 3, 2023

In a private project of mine I need to handle a lot of vectors and iterators, and as such I found myself writing things equivalent to

source.take(n).skip(1).chain(source.skip(n + 1))

or

source.enumerate().filter(|(i, _)| i != n_1 && i != n_2).map(|(_, x)| x)

pretty often. So I wondered if it would be worth adding a function with a signature like this to Itertools?

fn filter_position<P>(self, predicate: P) -> FilterPosition<Self, P>
    where Self: sized,
          P: FnMut(usize) -> bool,

I'd be happy to implement this. But if anyone has a better suggestion for the name/signature/the problem solution itself, I'd be happy to read it, too!

@scottmcm
Copy link
Contributor

scottmcm commented Apr 3, 2023

filter_map can help here. Something like this

source.enumerate().filter_map(|(i, x)| (i != n_1 && i != n_2).then_some(x))

Alternatively, you could do it with a stateful adapter. Perhaps

source.filter(index_filter(|i| i != n_1 && i != n_2))

via a helper like

fn index_filter<T>(mut p: impl FnMut(usize) -> bool) -> impl for<'a> FnMut(&'a T) -> bool {
    let mut next = 0;
    move |_| {
        let i = next;
        next += 1;
        p(i)
    }
}

@MultisampledNight
Copy link
Author

The filter_map solution is really elegant, thank you! Do you think then that filter_position would have a purpose? It's less to type, but also less powerful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants