3
$\begingroup$

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)

$\endgroup$

1 Answer 1

5
$\begingroup$
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}}}}
$\endgroup$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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