Created
October 31, 2012 18:49
-
-
Save martintrojer/3989043 to your computer and use it in GitHub Desktop.
sieve of eratosthenes + newton (lazy)
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 sqrtStream(x: Double): Stream[Double] = { | |
def improve(guess: Double) = (guess + x / guess) / 2 | |
lazy val guesses: Stream[Double] = 1 #:: (guesses map improve) | |
guesses | |
} | |
sqrtStream(4).take(10).toList |
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 sieve(s: Stream[Int]): Stream[Int] = | |
s.head #:: sieve(s.tail filter (_ % s.head != 0)) | |
def from(n: Int): Stream[Int] = n #:: from(n + 1) | |
val primes = sieve(from(2)) | |
primes.take(10).toList | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment