Reputation: 3903
Say I have the following function definition:
def print(input:Iterator[String]) : Iterator[String] = {
Iterator.continually {
val item = input.next
item + item
}
}
given the input
List("1", "2", "3").iterator
I want the output to be equal to
List("11", "22", "33").iterator
The problem is that when I use Iterator.continually
, I am forced to iterate through the list using a takeWhile
. I would like to be able to use any Iterator function that exists (fold, filter, etc...) without getting a "next on empty iterator" exception.
You can do this in F# using seq and yield. I was hoping that Iterator.continually
would be just as robust.
F# example:
seq {
for i in input |> yield i + i
}
P.S. I realize I could just compose a bunch of functions and then pass them to an Iterator function but I'm trying to compose Iterators in a way that I could in F#.
Upvotes: 1
Views: 537
Reputation: 33029
I think List.map
will do what you want. However, you might want to use Scala's for comprehension syntax, which the compiler just translates into a map
call. Here's a snippet from a test in my REPL. Seems to work.
scala> def print(input:Iterator[String]) : Iterator[String] =
| for (i <- input) yield i + i
print: (input: Iterator[String])Iterator[String]
scala> print( List("a", "b", "c").iterator )
res0: Iterator[String] = non-empty iterator
scala> res0.toList
res1: List[String] = List(aa, bb, cc)
Upvotes: 3