Last active
August 29, 2015 14:14
-
-
Save ChrisCoffey/8d66b53ad59d6d6c0e32 to your computer and use it in GitHub Desktop.
A Functional Prime Number Generator In Scala
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[Long] = 2 #:: prime3 | |
// performance: avoid redundant divide by two, so this starts at 3 | |
private val prime3: Stream[Long] = { | |
def next(i: Long): Stream[Long] = | |
if (prime(i)) | |
i #:: next(i + 2) | |
else | |
next(i + 2) // tail | |
3 #:: next(5) | |
} | |
private def prime(i: Long) = | |
prime3 takeWhile (math.sqrt(i).>= _) forall { i % _ != 0 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment