Created
May 15, 2010 13:51
-
-
Save abhin4v/402205 to your computer and use it in GitHub Desktop.
How to get the currently evaluated items in a Stream 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
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