I'd like to Fold over higher dimensional objects than lists. Semantically, the format would be something like FoldMulti[f, array, list]. As a precondition, Dimensions[array] == Length[list].
The motivating example is from the recent discussions about inverse of CoefficientList.
Let poly be some polynomial, and cl be the coefficient list e.g.
poly = a x^5 + (x + 2 y)^3 + x y z + 1;
vars = {x, y, z};
cl = CoefficientList[poly, vars];
In this example, array = cl is 3 dimensional, and poly has length 3. For each variable var in {x,y,z}, the function (#1 var + #2) & should be folded across cl, to recreate poly from the coefficient array cl.
The following code works:
Fold[
Function[{clinner, var}, Fold[(#1 var + #2) &, Reverse@clinner]],
cl,
vars
]
% - poly // Expand
(* 0 *)
but the problem is that's just a horribly complex bit of code that calls Fold twice.
The following works and is pretty enough! But it uses a different idiom.
polyFromCL[cl_, {}] := cl
polyFromCL[cl_, vars_] :=
polyFromCL[
Fold[(#1 First@vars + #2) &, Reverse@cl],
Rest@vars
]
polyFromCL[cl, vars]
% - poly // Expand
(* 0 *)
Can something like MapThread or Outer be made to do this elegantly?
Fold[FromDigits[Reverse[#1], #2] &, cl, {x, y, z}]like documentation suggests? – Kuba May 10 '15 at 15:41Outer[Fold[f, #1, #2] &, {{o,p}, {q,r}, {s,t}},{{u,v}, {w,x}, {y,z}},1]Maybe
– Histograms May 10 '15 at 16:40TensorContract[#,{level}]and the Tensor functions could be helpful.Tabletwice in a single line like that, I'm hoping to avoid usingFoldtwice in much the same way. – djp May 11 '15 at 00:35cwyozeg" :) or similar. – djp May 11 '15 at 00:39