public
Last active

  • Download Gist
tricky_gen2Trav.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.