Editor's note: This question uses some functions and types that were removed before Rust 1.0. The ideas are still valid but the code does not run in Rust 1.0.
I'm trying to solve Project Euler's problem #3 using Rust by implementing Eratosthenes Sieve as an iterator.
After some brain-exploding tries with lifetimes, I stopped here.
use std::iter::count;
struct EratosthenesStream<'a> {
sieve: &'a (Iterator + 'a),
}
impl<'a> EratosthenesStream<'a> {
fn new() -> EratosthenesStream<'a> {
EratosthenesStream {
sieve: &count(2, 1),
}
}
}
impl<'a> Iterator for EratosthenesStream<'a> {
type Item = isize;
fn next(&mut self) -> Option<isize> {
let prime = self.sieve.next().expect("Out of numbers");
self.sieve = self.sieve.filter(|&x| x % prime == 0);
Some(prime)
}
}
fn main() {
// let sieve = EratosthenesStream::new();
// for i in sieve.take(5) {
// println!("{}", i);
// }
}
Building that thing gives me:
Compiling problem3 v0.0.1 (file:///home/franza/Projects/euler-project-rust/problem3)
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:16:33: 16:45 error: the value of the associated type `Item` (from the trait `core::iter::Iterator`) must be specified
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:16 EratosthenesStream { sieve: &count(2, 1) }
^~~~~~~~~~~~
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:25:29: 25:56 error: type `&'a core::iter::Iterator + 'a` does not implement any method in scope named `filter`
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:25 self.sieve = self.sieve.filter(|&x| x % prime == 0);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:25:41: 25:42 error: the type of this value must be known in this context
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:25 self.sieve = self.sieve.filter(|&x| x % prime == 0);
^
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:25:36: 25:55 error: can't infer the "kind" of the closure, explicitly annotate it. e.g. `|&:| {}`
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:25 self.sieve = self.sieve.filter(|&x| x % prime == 0);
^~~~~~~~~~~~~~~~~~~
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:26:5: 26:16 error: mismatched types: expected `core::option::Option<isize>`, found `core::option::Option<<core::iter::Iterator as core::iter::Iterator>::Item>` (expected isize, found associated type)
/home/franza/Projects/euler-project-rust/problem3/src/main.rs:26 Some(prime)
^~~~~~~~~~~
error: aborting due to 5 previous errors
Could not compile `problem3`.
I'm starting out in Rust so I don't know a lot about this
UPDATE:
rustc 1.0.0-nightly (44a287e6e 2015-01-08 17:03:40 -0800)
cargo 0.0.1-pre-nightly (8c01b6b 2015-01-08 20:52:43 +0000)