How to get the first state of a iterator?

I need to create a vector with the states of an iterator for which the element satisfies a certain condition.
However, to do that, I would need to know the first state of an iterator (i.e. the default argument of iterator), in case the first element satisfies the condition. Is there a way to get it?

Perhaps I misunderstand the question, but it sounds like you are looking for

Required methods Brief description
iterate(iter) Returns either a tuple of the first item and initial state or nothing if empty

from the docs.

Perhaps you could provide more detail on what you are trying to achieve?

Thanks but that’s not what I am looking for. I would like to create a function g(f::Function, iter) that returns for an arbitrary iterator iter the vector of states for which the corresponding element satisfies f(x) = 0

The returned vector by g must satisfy following:

for state in g(f, iter)
   f(iterate(iter,  state)) == 0

For instance,

g(x -> x == 0, [0, 1, 0]) = [1, 3]

Note that, because the first element satisfies the condition, the function should return the first state of the iterator.

There is (semantically) no state for the first iterate call though? Some iterators might implement their iterate with a default value as the state but that is not required and not every iterator does this.

1 Like

As @kristoffer.carlsson says, unfortunately your question has no answer. It’s true that many iterators are implemented through

iterate(::Iterator, state=....)

but many others are not.

What you could do is represent state by (state,) and the empty state by (). Example:

function g(f, iter)
    zerostates = []
    curstate = ()
    i = iterate(iter, curstate...)
    while !isnothing(i)
        val, state = i
        curstate = (state,)
        iszero(f(val)) && push!(zerostates, curstate)
        i = iterate(iter, curstate...)
    return zerostates

But it has the downside that you now have a Vector{Any}. It’s probably as close as you’ll get, though.

1 Like

Thanks everyone!