Reverse view of an array


#1

While reviewing a recent pull request in Images.jl, I ran across this line:

    cum_pmf_sq_2 = reverse!(cumsum(reverse!(prob_mass_function_sq)))

Using reverse! is better than reverse here, but writing out the loops manually would certainly be more efficient. I’m wondering if it’s worthwhile to try to add some conveniences for this:

  1. Add a reverse or rev keyword to accumulate (and cumsum, cumprod, etc.)
  2. Add a ReverseView wrapper to a Vector, which reverses the indexes (and therefore iteration), but otherwise leaves the data alone.

@stevengj recently added Iterators.Reverse, but that doesn’t work here, as cumsum (which is based on accumulate) requires an AbstractArray, and Iterators.Reverse isn’t one of those.

I can, of course, make these additions in a package, but they seem general enough that perhaps they could be included in Base. Thoughts?

Cheers,
Kevin


#2

A ReverseView would compose better than extra keywords to functions. If the performance penalty is not too large, it would be my preferred solution, as a middle ground between optimized loops and copying operations.


#3

Is there a fundamental reason why accumulate couldn’t work with any iterator? It looks like we just need to fix that limitation.


#4

SubArray already supports this. Try view(a, lastindex(a):-1:firstindex(a)). (using Compat for firstindex and lastindex on 0.6.)

Having an accumulate function that works on iterators would be great, though it is tricky to make fast and type-stable. Here, however, note that cumsum on floating-point arrays is actually much more accurate than any iterator-based version because it uses pairwise summation. Also, I suspect that the original use-case in this thread might want to use cumsum! so that it could operate in-place, and that wouldn’t be possible for iterators.


#5

Just a side-track: isn’t it possible to use series math to do, for instance, cumsum! on Iterators?


#6

The iterator protocol in Julia provides no way to mutate the iterator contents.


#7

Oh right…