Home > Software design >  Shorten iterator by condition in rust
Shorten iterator by condition in rust

Time:12-11

I'm looking for some way to shorten an iterator by some condition. A bit like an inverse filter but it stops iterating at the first true value. Let's call it until(f). Where:

iterator.until(f)

Would return an iterator that only runs until f is true once.

Let's use an example of finding the next prime number.

We have some structure containing known primes and a function to extend it.

// Structure for caching known prime numbers
struct PrimeGenerator {
    primes:Vec<i64>
}

impl PrimeGenerator {

    // Create a new prime generator
    fn new()->Self{
        let primes = vec![2,3];
        Self {
            primes,
        }
    }
    
    // Extend the list of known primes by 1
    fn extend_by_one(&mut self){
        let mut next_option = self.primes.last().unwrap() 2;
        while self.iter().any(|x| next_option%x == 0) { // This is the relevant line
            next_option  = 2;
        }
        self.primes.push(next_option);
    }

}

Now this snippet is a bit too exhaustive as we should only have to check until the square root of next_option, so I was looking for a some method that would shorten the iterator based on some condition, so I could write something like:

self.iter().until(|x| x*x > next_option).any(|x| next_option%x == 0)

Is there any similar pattern available?

CodePudding user response:

Looks like your until is similar to inverted take_while.

self.iter().take_while(|x| x*x <= next_option).all(|x| next_option%x != 0)
  • Related