Lazy evaluation

I'm currently redoing the Project Euler maths problems again in Rust having done many of them in Python and Haskell previously. What thing I am missing from Haskell is the concept of lazy evaluation of lists.

Now I appreciate it doesn't perform as well compared to strict evaluation but curious if there are good, recommended libraries for doing the same with Rust? Or does it go totally against the ethos of the language?

As an example constructing an infinite list of primes that I can filter on.

Thanks for any help!

1 Like

A lazily evaluated list is close to an iterator in Rust. Can you pinpoint which part of the iterator API exactly feels unpleasant for the purpose of replacing the former with the latter?

1 Like

Sure!
Given a is_prime function:

let mut x = (0..).iter().filter(|&&x| is_prime(x));

let next_prime = x.next().unwrap();
let next_prime_again = x.next().unwrap();
for (i, v) in (&mut x).take(30).enumerate() {
    println!("{}th prime is {}", i + 2, v);
}
println!("33rd prime is {}", x.next().unwrap());

Or, you could create a structure which more efficiently finds primes and implement iterator on it yourself:

struct Primes {
    seen_primes: Vec<usize>,
    last_prime: Option<usize>,
}

impl Iterator for Primes {
    type Item = usize;
    fn next(&mut self) -> Self::Item {
        // Your algorithm of choice
    }
}

After this, with either the is_prime function, or the Primes structure, you can then filter (Again), map, take, skip, etc. They both implement Iterator.

2 Likes

Thank you. That's a great solution!

1 Like

Your example is helpful. What do you mean by “both” implement iterative?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.