Why not an inverse operator to ```accumulate```?

There is a function which I find useful is the inverse of accumulate. I’ll call it contrast. Basically, contrast`` is to diffwhataccumulateis tocumsum```. My implement (not necesaarily most efficient is:

contrast( op, v, init ) = [op( init, v[1] ); op.( v[1:end-1], v[2:end] )]

contrast( invop, accumulate( op, v ) ) == v module some initial value and where invop has the same relationship to op that + has to - (not exactly compositional inverses). I find this frequently useful but I think it is missing from the functional languages I’ve used. I’m in no way tied to the name above. I call it deaccumulate internally but a friend suggested contrast which I think is probably better.

4 Likes

In the Transducers.jl world, this is a special case of ScanEmit (which is a generalization of Scan, which is the transducer that performs accumulate):

using Transducers
Contrast(op, init) = ScanEmit((u, x) -> (op(u, x), x), init)

and then

julia> collect(Contrast(*, "a"), ["b", "c", "d", "e"])
4-element Vector{String}:
 "ab"
 "bc"
 "cd"
 "de"
3 Likes