4
$\begingroup$

Say I have a list:

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

I now want to apply a function, call it F to that list in a way that I go from the lowest to highest level, i.e.

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

Is there a function in Mathematica which does exactly that?

$\endgroup$
  • 4
    $\begingroup$ Why does the order for d and c change, and not for a and b? $\endgroup$ – Carl Woll Apr 29 at 22:30
  • $\begingroup$ My mistake, thank you for spotting that. I edited it. $\endgroup$ – amator2357 Apr 29 at 22:54
  • $\begingroup$ In your example it does not matter whether F is applied from the lowest level up or reverse. It it matters it may affect applicable solutions. $\endgroup$ – Kuba Apr 30 at 6:27
7
$\begingroup$
Replace[l, x_List :> F[x], All]

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

Also

ClearAll[f]
f[Except[_List, x_]] := x;
MapAll[f, l]

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

$\endgroup$
6
$\begingroup$

Another possibility, if you want just lists to acquire the F wrapper:

l /. List -> F@*List

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

$\endgroup$
4
$\begingroup$
F@*Reverse@Map[F@*Reverse, l, -2]

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

Fold[F[{#2, #1}] &, Flatten[l]]

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

$\endgroup$
  • $\begingroup$ I think that Flatten works in this trivial case but it will not "find" the levels in a more complex situation $\endgroup$ – J42161217 Apr 29 at 22:41
1
$\begingroup$

This works:

{{{a, b}, c}, d} //. {{s_?ListQ, t_?(Not@*ListQ)} :> {f[s], t}} // f

It's a bit hackish because of the separate invocation of f at the end, but it returns the desired result.

$\endgroup$

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.