Iterator filters don’t know the length of their output by default. However, there are cases where the program logic makes the length of the output known. How can we provide this info to improve the performance of subsequent uses of the filter, like collect?
Example
Let cube be an iterator that returns 9 CartesianIndexes (known length).
not33= Iterators.filter( c-> c.I != (3,3), cube )
We know from the program logic that exactly 1 item in cube will be filtered out, so length(not33) == 8 should be true.
I thought that Iterators.take should know its size, but that isn’t the case either. The only solution I can think of is to wrap my iterators in a custom type like take that will know its length at creation:
struct LengthfulIterator
iter
n::Int
end
Base.length(li::LengthfulIterator)= li.n
Base.iterate(li:LengthfulIterator, s)= ...
> not33= LengthfulIterator(
Iterators.filter( c-> c.I != (3,3), cube ),
8)
> length(not33) == 8
true
This does sound a bit contrived & verbose, and I wonder if there isn’t a more standard solution.