Skip to content

Instantly share code, notes, and snippets.

@logicmason
Last active December 27, 2015 10:59
Show Gist options
  • Save logicmason/7315562 to your computer and use it in GitHub Desktop.
Save logicmason/7315562 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Scala, using lazy evaluation. Example code in lines 4-5 prints out first 15 primes
def sieve(s: Stream[Int]): Stream[Int] = {
s.head #:: sieve(s.tail.filter(_ % s.head != 0))
}
val primes = sieve(Stream.from(2)) //infinite lazy stream
println((primes take 15).toList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment