I have a nested list:
list = {1, 2, {3, 4}, f[a], {2, h[b]}}
I would like to apply a function g
to all elements of the nested list (starting from top to bottom) that are not lists themselves. That is, I would like to obtain:
{g[1], g[2], {g[3], g[4]}, g[f[a]], {g[2], g[h[b]]}}
(Using Map[g, list, {-1}]
does not work, as it maps g
inside f
and h
)
The alternative I have ended up using is the following function:
mapAtLeavesOfList[g_, x_List] := Map[mapAtLeavesOfList[g, #] &, x]
mapAtLeavesOfList[g_, x_] := g[x]
mapAtLeavesOfList[g, list]
=> {g[1], g[2], {g[3], g[4]}, g[f[a]], {g[2], g[h[b]]}}
Any better suggestions?