Created
July 10, 2013 00:16
-
-
Save dorkrawk/5962472 to your computer and use it in GitHub Desktop.
Use lazy evaluation to compute primes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def from(n: Int): Stream[Int] = n #:: from(n + 1) | |
def sieve(s: Stream[Int]): Stream[Int] = s.head #:: sieve(s.tail filter (_ % s.head != 0)) | |
val primes = sieve(from(2)) | |
primes.take(10).toList // produces first 10 primes | |
primes.take(100).toList // produces first 100 primes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment