aochagavia
aochagavia

Reputation: 6246

Lazy filtering of a range?

I was trying to calculate the first x prime numbers by using the following line of code:

(1 to Int.MaxValue).filter(is_prime _).take(x)

However, the program just didn't stop and I had to close it (I didn't want to wait until Int.MaxValue was reached). How could I rewrite this to work in normal time while mantaining the simplicity?

Upvotes: 1

Views: 727

Answers (2)

DNA
DNA

Reputation: 42607

You can also use a Stream (or Iterator - see the comments below)

Stream.from(1).filter(is_prime).take(x)

Upvotes: 5

Noah
Noah

Reputation: 13959

Range will traverse the whole collection with filter. Try using a view instead:

(1 to Int.MaxValue).view.filter(is_prime _).take(x)

Upvotes: 3

Related Questions