Iteration in Julia

Yesterday I wanted to iterate over the collection in reverse order. I found the reverse function, but it does not return an iterator, but actually creates a reverse collection.

Apparently, the reverse iterator was used earlier, which was removed several years ago. I can also find a link for something (like?) Called Order.Reverse , but that doesn't seem to be my question.

There are many interesting iteration patterns in the Iterators.jl package, but apparently not a reverse iteration.

Of course, I can use the reverse function, and in some cases, for example, reverse(eachindex(c)) , which returns a reverse iterator, but I would prefer a common reverse iterator.

Is there such a thing?

+7
iteration reverse-iterator julia-lang
source share
1 answer

Jeff's comment when he removed the reverse iterator three years ago (into the problem you were contacting ) is also relevant today:

I am very grateful for removing this, as it just does not work. Unlike everything else in iterator.jl, it depends on indexing, not iteration, and doesnโ€™t even work on everything that is indexed (for example, UTF8String). I hate having land mines in the Base.

At the most basic level, iterators only know how to do three things: start the iteration, get the next element, and check if the iteration is complete. To create an iterator that does not highlight these primitives, you will need the O (n ^ 2) algorithm: go through the entire iterator, counting when you go until you find the last element. Then again go to the iterator, only this time stopping at the penultimate element. Of course, it does not stand out, but it will be slower than just collecting the iterator into an array and then indexing back. And it will be completely split into iterators with one shot (e.g. eachline ). Thus, it is simply not possible to create an efficient general inverse iterator.

Note that reverse(eachindex(c)) does not work at all:

 julia> reverse(eachindex(sprand(5,5,.2))) ERROR: MethodError: no method matching reverse(::CartesianRange{CartesianIndex{2}}) 

One alternative that will work with offset arrays is reverse(linearindices(c)) .

+5
source share

All Articles