5
$\begingroup$

I would like to FoldList a simple function, with desired output:

f[a,b,1]
f[b,c,1]
f[c,a,1]

f[f[a,b,1],f[b,c,1],2]
f[f[b,c,1],f[c,a,1],2]
f[f[c,a,1],f[a,b,1],2]

f[f[f[a,b,1],f[b,c,1],2],f[f[b,c,1],f[c,a,1],2],3]
f[f[f[b,c,1],f[c,a,1],2],f[f[c,a,1],f[a,b,1],2],3]
f[f[f[c,a,1],f[a,b,1],2],f[f[a,b,1],f[b,c,1],2],3]

which I can hack with

t2[li_] := Take[#, 2] &@RotateLeft[li, #] & /@ Range[0, Length@li - 1];
sf[n_] := "" <> ToString[# - 1] <> "], " <> ToString[# - 2] <> "]" -> 
 "" <> ToString[# - 1] <> "], " <> ToString[#] <> "]" &@n;
nl = ToExpression@With[{string = ToString /@ 
     Rest[FoldList[f[#[[1]], #[[2]]] & /@ t2@# &, {a, b, c}, 
     Range@#]]}, Fold[StringReplace, string,
     Flatten[{{"]" -> ", 1]", "1], 1]" -> "1], 2]"}, 
     sf /@ Range[3, #]}, 1]]] &[5];

Column[Column /@ Take[nl, 3]]

with huge inefficiencies for large n (there is no problem with the t2 part of the function). All I want to do is add in indexing into the last position of f[_,_,_].

I'd really like to do it with something simple like

FoldList[f[#[[1]], #[[2]],#2] & /@ t2@# &, {a, b, c}, Range@3]

but I can't use #2 since MapThread gets in the way. I know I am over-complicating things - what is a more sensible way to achieve the above?

$\endgroup$

2 Answers 2

5
$\begingroup$

Here is one possibility. Create a helper function:

g[l_List,i_] := f[##, i]& @@@ Partition[l, 2, 1, 1]

Then, fold this helper function:

FoldList[g, {a, b, c}, {1, 2, 3}]

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

$\endgroup$
1
  • $\begingroup$ great - much better! Thank you :) $\endgroup$
    – martin
    Sep 18, 2017 at 19:08
0
$\begingroup$

here is another option, though it is not as good as the code provided by Carl

t3[j_List, l_, m_] := Append[ Take[RotateLeft[j, l], 2], m]
h[p_List, i_ ] :=   f @@@ MapIndexed[  t3[p, #, i] &  , Range[0, 2]]
FoldList[h, {a, b, c}, {1, 2, 3 }]  
$\endgroup$

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.