What is the easiest way to map an arbitrary nested expr list to an unflatten function unflatten that expr==unflatten@@Flatten@expr ?
Motivation: Compile can only process full arrays (something I just found out, but not from the error message), so the idea is to use unflatten along with a compiled version of the smoothed expression:
fPrivate=Compile[{x,y},Evaluate@Flatten@expr]; f[x_?NumericQ,y_?NumericQ]:=unflatten@@fPrivate[x,y]
An example of a solution to a less general problem: I really need to calculate all the derivatives for a given multidimensional function to some order. In this case, I make my way like this:
expr=Table[D[x^2 y+y^3,{{x,y},k}],{k,0,2}]; unflatten=Module[{f,x,y,a,b,sslot,tt}, tt=Table[D[f[x,y],{{x,y},k}],{k,0,2}] /. {Derivative[a_,b_][_][__]-> x[a,b], f[__]-> x[0,0]}; (Evaluate[tt/.MapIndexed[#1->sslot[#2[[1]]]&, Flatten[tt]]/. sslot-> Slot]&) ] Out[1]= {x^2 y + y^3, {2 xy, x^2 + 3 y^2}, {{2 y, 2 x}, {2 x, 6 y}}} Out[2]= {#1, {#2, #3}, {{#4, #5}, {#5, #7}}} &
It works, but is neither elegant nor general.
Edit: Here is the version of the security solution provided by aaz:
makeUnflatten[expr_List]:=Module[{i=1}, Function@Evaluate@ReplaceAll[ If[ListQ[
It works:
In[2]= makeUnflatten[expr] Out[2]= {#1,{#2,#3},{{#4,#5},{#6,#7}}}&