A prime number algorithm in Scala (with the Scala Stream class)

Daniel Sobral posted this prime number algorithm in Scala on this SO page way back in 2010:

def primeStream(s: Stream[Int]): Stream[Int] =
    Stream.cons(s.head, primeStream(s.tail filter { _ % s.head != 0 }))
val primes = primeStream(Stream.from(2))

If you’re interested in the output of that algorithm you can paste that code into the Scala REPL, and then invoke it like this:

primes take 10 foreach println

If I have time I’ll write more about this algorithm in the future, but for now I’m digging into the Scala Stream class (I now have a Scala Stream class tutorial), and I just came across this example.

Note: The cons function shown is not defined in the Scala Stream class, but is in the Scala Stream object. The Scaladoc states that it is, “an alternative way of building and matching Streams using Stream.cons(head, tail).”