Skip to content

Instantly share code, notes, and snippets.

@jeffreyolchovy
Created August 30, 2012 15:15
Show Gist options
  • Save jeffreyolchovy/3530567 to your computer and use it in GitHub Desktop.
Save jeffreyolchovy/3530567 to your computer and use it in GitHub Desktop.
Recursive Streams in Scala
import scala.math.{BigInt, BigDecimal}
object RecursiveStreams
{
// natural numbers
lazy val N: Stream[BigInt] = Stream.cons(BigInt(1), N.map(_ + 1))
// fibonacci series
lazy val fib: Stream[BigInt] = Stream.cons(BigInt(0), Stream.cons(BigInt(1), fib.zip(fib.tail).map(a => a._1 + a._2)))
// factorials
lazy val fac: Stream[BigInt] = Stream.cons(BigInt(1), fac.zip(N).map(a => a._1 * a._2))
// pi / 4
lazy val piOver4: Stream[Double] = Stream.cons(1d, N.map(a => (1 - (a.toDouble % 2) * 2) / (2 * a.toDouble + 1)))
def estimatePi(n: Int): Double = piOver4.take(n).sum * 4
def main(args: Array[String]) {
assert(N(0) == 1)
assert(fib(0) == 0)
assert(fac(0) == 1)
assert(fib(5) == 5)
assert(fac(5) == 120)
println("First 10 natural numbers: %s".format(N.take(10).mkString(" ")))
println("First 10 fibonacci numbers: %s".format(fib.take(10).mkString(" ")))
println("First 10 factorials: %s".format(fac.take(10).mkString(" ")))
println("Pi estimate: %s".format(estimatePi(5000)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment