Skip to content

Instantly share code, notes, and snippets.

@grzesiak
Created September 29, 2010 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grzesiak/603569 to your computer and use it in GitHub Desktop.
Save grzesiak/603569 to your computer and use it in GitHub Desktop.
object Main {
def toStreamWithThread[T](generator: (T=>Unit)=>Unit): Stream[T] = {
val queue = new java.util.concurrent.SynchronousQueue[Option[T]]
new Thread(
new Runnable {
def run() {
generator { (Some(_:T)) andThen (queue.put(_)) }
queue.put(None)
}
}
).start()
Stream.continually(queue.take).takeWhile(_.isDefined).map(_.get)
}
def toTraversable( data : (Int => Unit) => Unit) = {
new Traversable[Int] {
def foreach[U](f : Int => U) = {
data( f(_) : Unit)
}
}
}
def main(args: Array[String]) {
def data(block: Int => Unit) {
for (i <- 0 to 10) {
println("It is " + i + " here!")
block(i)
}
}
println("--- We want all ints")
toTraversable(data).foreach { i =>
println("and I like " + i + " very much!")
}
println("\n--- Now we want just first 7 ints (toStreamWithThread)")
toStreamWithThread(data).take(7).foreach { i =>
println("and I like " + i + " very much!")
}
println("\n--- Now we want just first 7 ints (toTraversable)")
toTraversable(data).take(7).foreach { i =>
println("and I like " + i + " very much!")
}
}
}
RESULT:
--- We want all ints
It is 0 here!
and I like 0 very much!
It is 1 here!
and I like 1 very much!
It is 2 here!
and I like 2 very much!
It is 3 here!
and I like 3 very much!
It is 4 here!
and I like 4 very much!
It is 5 here!
and I like 5 very much!
It is 6 here!
and I like 6 very much!
It is 7 here!
and I like 7 very much!
It is 8 here!
and I like 8 very much!
It is 9 here!
and I like 9 very much!
It is 10 here!
and I like 10 very much!
--- Now we want just first 7 ints (toStreamWithThread)
It is 0 here!
It is 1 here!
and I like 0 very much!
It is 2 here!
and I like 1 very much!
It is 3 here!
and I like 2 very much!
It is 4 here!
and I like 3 very much!
It is 5 here!
and I like 4 very much!
It is 6 here!
and I like 5 very much!
It is 7 here!
and I like 6 very much!
--- Now we want just first 7 ints (toTraversable)
It is 0 here!
It is 1 here!
It is 2 here!
It is 3 here!
It is 4 here!
It is 5 here!
It is 6 here!
It is 7 here!
and I like 0 very much!
and I like 1 very much!
and I like 2 very much!
and I like 3 very much!
and I like 4 very much!
and I like 5 very much!
and I like 6 very much!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment