Skip to content

Instantly share code, notes, and snippets.

@dorkrawk
Created July 10, 2013 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dorkrawk/5962472 to your computer and use it in GitHub Desktop.
Save dorkrawk/5962472 to your computer and use it in GitHub Desktop.
Use lazy evaluation to compute primes.
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