3

Can we construct a function f, g in mathematica such that

For any list L,

g[Flatten[L],f[L]] becomes L.

More explanation :
f[..] outputs the structure of a given list L (nested structure)
g[..,..] restores original list L, from flattened list and the structure of the list.

I bet there is a built-in function or someone else already have made it.

This question is related with generalization of

Applying f for a part of list (MapAt is slow)

imida k
  • 4,285
  • 9
  • 17

1 Answers1

5
ClearAll[f, g]
f = Identity;
g = Internal`CopyListStructure[#2, #] &;

Example:

list = {{1, {2, 3}, {4, 5}}, {{{6, 7}}}, {{8, {{{9}}}}, {10, 11}}};

g[Flatten @ list, f @ list] == list

True

Note: Internal`CopyListStructure[arg1_, arg2_] requires Length[Flatten @ arg1] == Length @ arg2:

Examples:

Internal`CopyListStructure[{{a, {b, {{{{{c}}}}, d}}}}, {2, 3, 4, 1}]
{{2, {3, {{{{{4}}}}, 1}}}}
Internal`CopyListStructure[{{a, {b, {c}}}}, {{x, y}, {r, s, t, {u}}, 1}]
{{{x, y}, {{r, s, t, {u}}, {1}}}}
kglr
  • 394,356
  • 18
  • 477
  • 896
  • Always thank you! I posted related problem here : https://mathematica.stackexchange.com/questions/264838 – imida k Mar 08 '22 at 16:05