NLinker

Generators Python vs Scala

Nov 20th, 2018
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.60 KB | None | 0 0
  1. // Python version
  2. def stream(count):
  3.     for i in range(count):
  4.         print("Generating new object ({})".format(i))
  5.         yield "string_{}".format(i)
  6.  
  7. for item in stream(10):
  8.     print(item)
  9.  
  10.  
  11. // Scala version
  12. def generate(count: Int): Iterator[String] = {
  13.     def stream(current: Int): Stream[String] = {
  14.         if (current < count) {
  15.             s"string_$current" #:: stream(current + 1)
  16.         } else {
  17.             Stream.empty[String]
  18.         }
  19.     }
  20.  
  21.     stream(0).iterator
  22. }
  23.  
  24. val stream: Iterator[String] = generate(10)
  25. while (stream.hasNext) {
  26.     println(stream.next())
  27. }
Add Comment
Please, Sign In to add comment