# Returning the outputs of a nested structure

Say we have a list

l = {{{a, b}, c}, d}


To which we then apply a function F in the following manner

Replace[l, x_List :> F[x], All]


F[{F[{F[{a, b}], c}], d}]

Is there away of extracting the outputs of each application of F to l, so that we get a list

{F[{a,b}],F[{F[{a,b}],c}],F[{F[{F[{a, b}], c}], d}]}

?

• Try with Sow+Reap
– Kuba
Commented Apr 30, 2019 at 9:27

Using @Kuba 's suggestion:

Reap[Replace[l, x_List :> Sow[F[x]], All]]

{F[{F[{F[{a, b}], c}], d}], {{F[{a, b}], F[{F[{a, b}], c}], F[{F[{F[{a, b}], c}], d}]}}}


So to get precisely what I want

Reap[Replace[l, x_List :> Sow[F[x]], All]][[2]]

{{F[{a, b}], F[{F[{a, b}], c}], F[{F[{F[{a, b}], c}], d}]}}


I think I'd do it with FoldList. Like so:

l = {{{a, b}, c}, d};
FoldList[F[{#1, #2}] &, Flatten @ l] // Rest


{F[{a, b}], F[{F[{a, b}], c}], F[{F[{F[{a, b}], c}], d}]}

• That is very nice! Thank you. Commented Apr 30, 2019 at 11:13
• @amator2357. Thanks for accepting my answer. But I don't understand why you considered it worth an acceptance but not an up-vote. You are aware, aren't you, that you can do both. Commented Apr 30, 2019 at 11:21
• Yes, I am aware, it wasn't intentional tho, I thought that I did upvote it. Thanks for pointing it out :) Commented Apr 30, 2019 at 11:24
• @amator2357. Your welcome and thank you for the up-vote. Commented Apr 30, 2019 at 11:25

Another variation:

Last @ Reap[l /. List -> Sow @* F @* List]


{{F[{a, b}], F[{F[{a, b}], c}], F[{F[{F[{a, b}], c}], d}]}}

You can also use Cases to extract the elements with Head F:

r = Replace[l, x_List :> F[x], All];
Cases[r, _F, All]


{F[{a, b}], F[{F[{a, b}], c}], F[{F[{F[{a, b}], c}], d}]}