Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created May 15, 2010 13:51
Show Gist options
  • Save abhin4v/402205 to your computer and use it in GitHub Desktop.
Save abhin4v/402205 to your computer and use it in GitHub Desktop.
How to get the currently evaluated items in a Stream in Scala
import annotation.tailrec
import collection.immutable.List
import collection.immutable.Stream.{Empty,Cons}
object EvaluatedStream {
def evaluatedItems[T](stream: => Stream[T]): List[T] = {
@tailrec
def inner(s: => Stream[T], acc: List[T]): List[T] = s match {
case Empty => acc
case c: Cons[T] => if (c.tailDefined) {
inner(c.tail, acc ++ List(c.head))
} else { acc }
}
inner(stream, List())
}
def main(args: Array[String]) {
val s = Stream.iterate(1) { _ + 1 }
s takeWhile { _ < 10} force
val list: List[Int] = evaluatedItems(s)
assert(list == List(1, 2, 3, 4, 5, 6, 7, 8, 9))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment