How to combine Nest and list Part

I have a list $L$ of Length $n\geq6$ and a function $f$ that, when applied to $L$, generates $n-5$ lists $\mathscr{L}_i$ of Length $n-1$ (at the outermost level). I want to then apply $f$ to each $\mathscr{L}_i$, then repeat with the generated lists and keep doing that until I get $(n-5)!$ lists of length 5 (which I suppose is right).

I only wanna do this for small $n$, so performance is not a problem, I just can't figure out the way to do it: I've been trying Nest, NestWhile and the List versions together with Table to access the generated list elements but to no success.

To show you exactly what I'm doing, for $n=8$, I have e.g.

f[Range[8]]
Flatten[Table[f[%[[p]]], {p, Length[%]}], 1]
Flatten[Table[f[%[[p]]], {p, Length[%]}], 1]


for which the output is

{{1, 2, {3, 4}, 5, 6, 7, 8},
{1, 2, 3, {4, 5}, 6, 7, 8},
{1, 2, 3, 4, {5, 6}, 7, 8}}

{{1, 2, {{3, 4}, 5}, 6, 7, 8},
{1, 2, {3, 4}, {5, 6}, 7, 8},
{1, 2, {3, {4, 5}}, 6, 7, 8},
{1, 2, 3, {{4, 5}, 6}, 7, 8},
{1, 2, {3, 4}, {5, 6}, 7, 8},
{1, 2, 3, {4, {5, 6}}, 7, 8}}

{{1, 2, {{{3, 4}, 5}, 6}, 7, 8},
{1, 2, {{3, 4}, {5, 6}}, 7, 8},
{1, 2, {{3, {4, 5}}, 6}, 7, 8},
{1, 2, {3, {{4, 5}, 6}}, 7, 8},
{1, 2, {{3, 4}, {5, 6}}, 7, 8},
{1, 2, {3, {4, {5, 6}}}, 7, 8}}


(it doesn't really matter what f does*) however, when I try to do this with a one-liner I don't get what I expect,

NestWhileList[
Flatten[Table[f[# &[[p]]], {p, Length[# &]}], 1],
f[Range[8]], Length[#] & < 3!]


just gives

{{{1, 2, {3, 4}, 5, 6, 7, 8},
{1, 2, 3, {4, 5}, 6, 7, 8},
{1, 2, 3, 4, {5, 6}, 7, 8}}}


* I didn't think the particular definition of f would matter, but since it is mentioned in the comments, this is it:

f[L_] := Table[
Delete[ReplacePart[L, p+1 -> {L[[p+1]], L[[p+2]]}], p+2]
, {p, 2, Length[L]-4}] /; Length[L] >= 6

• Your & seems to be in awkward places. Try NestWhileList[Flatten[Table[f[#[[p]]], {p, Length[#]}], 1] &, f[Range[8]], Length[#] & < 3!]. Jul 26, 2016 at 12:31
• Yes, I thought about that; however I try this and it doesn't work Jul 26, 2016 at 12:39
• You claim that it doesn't matter what f does and then supply an example where f produces an output that matches the description in the first paragraph. Really a crime not to supply f in this question. Jul 26, 2016 at 16:46
• I apologize, I've added explicitly the definition of f. Jul 27, 2016 at 9:11

f[L_List] := ConstantArray[ConstantArray[0, # - 1], # - 5] &[Length[L]]

n = 9;
ini = ConstantArray[0, n];


For array structure:

Fold[Map[f, #, {#2}] &, ini, Range[0, n - 6]]


Or if you want a flat result:

Nest[Flatten[Map[f, #], 1] &, {ini}, n - 5]

• I used your second option with NestList and had to set n-6, but it works fine Jul 26, 2016 at 12:40