Obtaining the type of the state object returned by Iterate

An issue I’ve run into is that if you have a container type T, in general it isn’t possible to obtain the type of state returned by iterate in the same way as you can get eltype(T) since there is no (let’s call it iterate_statetype(T) ) function in the iterator protocol.

This makes it difficult to efficiently save the state object returned by iterate in a container, for example if you are rewriting a recursive algorithm as an iterative one and are pushing the “stack frames” into a vector.

3 Likes

Base.Iterators.Stateful has some tricks to figure this out.

1 Like

That was very useful, thank you!

Glancing at the Base.Iterators.Stateful code, it seems the relevant functionality relies on internal Julia functions? Is there perhaps a better way for code that’s not a part of the Julia project?

There’s no documented official way to get the “iterator eltype”. Possible solutions rely on type inference, and basically boil down to Core.Compiler.return_type(Base._iterator_upper_bound, Tuple{T}).