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 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) | |
} |
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