# Applying a function to a nested list

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?

• Why does the order for d and c change, and not for a and b? Apr 29 '19 at 22:30
• My mistake, thank you for spotting that. I edited it. Apr 29 '19 at 22:54
• 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.
– Kuba
Apr 30 '19 at 6:27

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

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

l /. List -> F@*List


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

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

• I think that Flatten works in this trivial case but it will not "find" the levels in a more complex situation Apr 29 '19 at 22:41

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.