# Is there an operation like map but with accumulated state?

**URL:** <https://discourse.julialang.org/t/is-there-an-operation-like-map-but-with-accumulated-state/93581>\
**Category:** General Usage\
**Created:** [January 26, 2023, 3:43pm UTC](https://discourse.julialang.org/t/is-there-an-operation-like-map-but-with-accumulated-state/93581 "2023-01-26T15:43:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![taotree](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/taotree/32/31982_2.png) [@taotree](https://discourse.julialang.org/u/taotree)\
**Post date:** [January 26, 2023, 3:43pm UTC](https://discourse.julialang.org/t/is-there-an-operation-like-map-but-with-accumulated-state/93581/1 "2023-01-26T15:43:10Z")

</div>

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:

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

```

which outputs:

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

```

---

<div class="post-metadata">

**Author:** ![contradict](https://avatars.discourse-cdn.com/v4/letter/c/ac91a4/32.png) [@contradict](https://discourse.julialang.org/u/contradict)\
**Post date:** [January 26, 2023, 3:49pm UTC](https://discourse.julialang.org/t/is-there-an-operation-like-map-but-with-accumulated-state/93581/2 "2023-01-26T15:49:48Z")

</div>

Maybe [`accumulate`](https://docs.julialang.org/en/v1/base/arrays/#Base.accumulate)

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

```

---

<div class="post-metadata">

**Author:** ![taotree](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/taotree/32/31982_2.png) [@taotree](https://discourse.julialang.org/u/taotree)\
**Post date:** [January 27, 2023, 2:35pm UTC](https://discourse.julialang.org/t/is-there-an-operation-like-map-but-with-accumulated-state/93581/3 "2023-01-27T14:35:30Z")

</div>

> [@contradict](#):
>
> Maybe [`accumulate`](https://docs.julialang.org/en/v1/base/arrays/#Base.accumulate)

Exactly what I was looking for. Thank you!
