Sunday, 25 December 2011

Lazy prime numbers in Scala

def primes : Stream[Int] = {
def findNextPrime(primes: List[Int])={
var i = primes.head+1
while(primes.exists(x => i % x == 0)){i+=1}
i
}
def prim(primes:List[Int]): Stream[Int] = primes match{
case Nil => 1 #:: 2 #:: prim(List(2))
case _ => {
val next = findNextPrime(primes)
next #:: prim(next::primes)
}
}
prim(Nil)
}
view raw gistfile1.scala hosted with ❤ by GitHub

The key to understanding this example is the #:: operator. It is very similar to :: for collections. The difference is that it doesn't evaluate the right hand side argument immediately. Instead it keeps it's reference as a function and evaluates it only when needed. The evaluation is deferred until the actual element is needed.

No comments:

Post a Comment