6
$\begingroup$

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

$\endgroup$

2 Answers 2

8
$\begingroup$
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]}

$\endgroup$
2
  • $\begingroup$ 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 $\endgroup$
    – user62657
    Commented Jan 30, 2019 at 9:37
  • $\begingroup$ @user62657, thank you for the accept; and welcome to mma.se. $\endgroup$
    – kglr
    Commented Jan 30, 2019 at 9:50
4
$\begingroup$

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]}
$\endgroup$
2
  • 1
    $\begingroup$ 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. $\endgroup$ Commented Jan 30, 2019 at 8:35
  • $\begingroup$ @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) $\endgroup$
    – rafalc
    Commented Jan 30, 2019 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.