# How to make FoldListIndexed ie FoldList with an index or iterator?

Is there a functional or inbuilt way to add an index to FoldList?

i.e.:

FoldListIndex[f,x,{a,b,...}]


gives

{x,f[x,a,1],f[f[x,a,1],b,2],...}


My current method with a loop is quite unsatisfactory

## 2 Answers

foldIndexedList = Module[{i = 1, f = #}, FoldList[f[##, i++] &, ##2]] &;
foldIndexedList[f, x, {a, b, c, d}]


{x, f[x, a, 1], f[f[x, a, 1], b, 2], f[f[f[x, a, 1], b, 2], c, 3], f[f[f[f[x, a, 1], b, 2], c, 3], d, 4]}

foldIndexedList2 =  Module[{f = #},
FoldList[f[#, ## & @@ #2] &, #2, MapIndexed[{#, #2[[1]]} &]@#3]] &;
foldIndexedList2[f, x, {a, b, c, d}]


{x, f[x, a, 1], f[f[x, a, 1], b, 2], f[f[f[x, a, 1], b, 2], c, 3], f[f[f[f[x, a, 1], b, 2], c, 3], d, 4]}

• Thanks rafalc and kglr for the answers. I selected kglr as it resulted in a faster function for my specific implementation and it worked with foldIndexedList[f,{a,b,c,d}] as well Commented Jan 30, 2019 at 9:37
• @user62657, thank you for the accept; and welcome to mma.se.
– kglr
Commented Jan 30, 2019 at 9:50

You can try

FoldListIndexed[f_, x_, lst_] :=
FoldList[
Function[{a, b}, f[a, Sequence @@ b]],
x,
Transpose[{lst, Range @ Length @ lst}]
]


and then

In[4]:= FoldListIndexed[f, x, {a, b, c, d}]

Out[4]= {x, f[x, a, 1], f[f[x, a, 1], b, 2],
f[f[f[x, a, 1], b, 2], c, 3], f[f[f[f[x, a, 1], b, 2], c, 3], d, 4]}

• Nice solution, but I would rather avoid using Block, especially for functions living in Global . Imagine that g has been defined globally, and is called by f - then this code will break it in a very non-obvious way. I would rather use a pure function for g, and With instead of Block`. Commented Jan 30, 2019 at 8:35
• @LeonidShifrin thank you, I have edited my answer following your suggestions (got rid of Block entirely - I think the code is still readable even without the helper variable) Commented Jan 30, 2019 at 8:47