Is there an operation like map but with accumulated state?

I want to do a map operation, but have the previous calculated value available to each step. Or put another way, I want to run a foldl but output a collection of the results of each step. It seems like this should be a common named operation, but I don’t know.

It can be done in a foldl by having each step push onto a Vector and return that vector, but it seems like there ought to be a first class operation that does this rather than some workaround.

I found some articles about “Mapping with state” which discuss using a State monad, but that seems a bit more complicated than expected.

An example implementation:

function maps(f, v, init)
    s = init
    map(v) do x
        s = f(s, x)
    end
end

which outputs:

> bt.maps((a, x) -> a * x, [1,2,3,4], 10)
4-element Vector{Int64}:
  10
  20
  60
 240

Maybe accumulate

julia> accumulate(*, [1,2,3,4], init=10)
4-element Vector{Int64}:
  10
  20
  60
 240
5 Likes

Exactly what I was looking for. Thank you!