5
$\begingroup$

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}]}

?

$\endgroup$
1
  • 1
    $\begingroup$ Try with Sow+Reap $\endgroup$
    – Kuba
    Commented Apr 30, 2019 at 9:27

4 Answers 4

7
$\begingroup$

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

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}]}

$\endgroup$
4
  • $\begingroup$ That is very nice! Thank you. $\endgroup$
    – amator2357
    Commented Apr 30, 2019 at 11:13
  • $\begingroup$ @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. $\endgroup$
    – m_goldberg
    Commented Apr 30, 2019 at 11:21
  • $\begingroup$ Yes, I am aware, it wasn't intentional tho, I thought that I did upvote it. Thanks for pointing it out :) $\endgroup$
    – amator2357
    Commented Apr 30, 2019 at 11:24
  • $\begingroup$ @amator2357. Your welcome and thank you for the up-vote. $\endgroup$
    – m_goldberg
    Commented Apr 30, 2019 at 11:25
3
$\begingroup$

Another variation:

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

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

$\endgroup$
3
$\begingroup$

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}]}

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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