Skip to content

Instantly share code, notes, and snippets.

@nelanka
Last active August 29, 2015 14:14
Show Gist options
  • Save nelanka/2a4a4ae63b98d8aea983 to your computer and use it in GitHub Desktop.
Save nelanka/2a4a4ae63b98d8aea983 to your computer and use it in GitHub Desktop.
Stream Examples
def fib(n: Int): Stream[Int] = n match {
case 0 ⇒ 0 #:: fib(1)
case 1 ⇒ 1 #:: fib(2)
case _ ⇒ (fib(n - 1).head + fib(n - 2).head) #:: fib(n + 1)
}
fib(0) take 10 foreach println
// From http://www.scala-lang.org/api/current/#scala.collection.immutable.Stream
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
fibs take 5 foreach println
/*
tail is everything but the head. Zipping gives us:
(Stream(0, ?), Stream(1, ?))
map over that to add up the heads of the zipped stream with { n => n._1 + n._2 }
*/
// Finally, you can do this without creating two streams and zipping and thus creating lots of objects
// Notice that the call to loop now becomes tail recursive
lazy val fib: Stream[Int] = {
def loop(h: Int, n: Int): Stream[Int] = h #:: loop(n, h + n)
loop(0, 1)
}
// Factorial
lazy val factorial: Stream[Int] = {
def loop(n: Int): Stream[Int] = (1 to n).product #:: loop(n + 1)
loop(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment