TransWikia.com

Distribute a nested list

Mathematica Asked on March 22, 2021

I would need a function that distributes a nested list in a specified position.

A sample of this function could be:

try={{1,{a,b,c},2},3,4,{5,6}}
DistributeNested[try,{1,2}]

which output would be

{{{1,a,2},3,4,{5,6}},{{1,b,2},3,4,{5,6}},{{1,c,2},3,4,{5,6}}}

How can I realise such a function?

One Answer

Thread[MapAt[Thread, try, {1}], List, 1]
{{{1, a, 2}, 3, 4, {5, 6}}, 
 {{1, b, 2}, 3, 4, {5, 6}}, 
 {{1, c, 2}, 3, 4, {5, 6}}}

Update: Using the second and third arguments of Thread you can specify the heads and positions of arguments to thread over:

try2 = {{1, {a, b, c}, {e, f, g}}, 3, 4, {5, 6}};

Thread[MapAt[Thread, try2, {1}], List, 1]
{{{1, a, e}, 3, 4, {5, 6}}, 
 {{1, b, f}, 3, 4, {5, 6}}, 
 {{1, c, g}, 3, 4, {5, 6}}} 
Thread[MapAt[Thread[#, List, {2}] &, try2, {1}], List, 1]
{{{1, a, {e, f, g}}, 3, 4, {5, 6}},
 {{1, b, {e, f, g}}, 3, 4, {5, 6}},
 {{1, c, {e, f, g}}, 3, 4, {5, 6}}}
Thread[MapAt[Thread[#, List, {3}] &, try2, {1}], List, 1]
{{{1, {a, b, c}, e}, 3, 4, {5, 6}},
 {{1, {a, b, c}, f}, 3, 4, {5, 6}},
 {{1, {a, b, c}, g}, 3, 4, {5, 6}}}
try3 = {{1, foo[a, b, c], bar[e, f, g]}, 3, 4, {5, 6}} ;

Thread[MapAt[Thread[#, foo] &, try3, {1}], List, 1]
{foo[{1, a, bar[e, f, g]},
     {1, b, bar[e, f, g]},
     {1, c, bar[e, f, g]}], 3, 4, {5, 6}}
Thread[MapAt[Thread[#, bar] &, try3, {1}], List, 1]
{bar[{1, foo[a, b, c], e},
     {1, foo[a, b, c], f},
     {1, foo[a, b, c], g}], 3, 4, {5, 6}}
Thread[MapAt[Thread[#, foo] &, try3, {1}], foo, 1]
foo[{{1, a, bar[e, f, g]}, 3, 4, {5, 6}}, 
    {{1, b, bar[e, f, g]}, 3, 4, {5, 6}}, 
    {{1, c, bar[e, f, g]}, 3, 4, {5, 6}}]

Correct answer by kglr on March 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP