Let's say I have some ragged list. If some elements have some depth $n$, then is there a way I can map a function to only those elements?
I.e., for some list foo
,
foo = {1, {2, 3}, {4, 5, {6, 7}}, {8}, {9}}
The result should then be for $n=2$:
{1, {bar[2], bar[3]}, {4, 5, {6, 7}}, {bar[8]}, {bar[9]}}
I want to apply a function bar to all parts of it that are of depth 2, and depth 2 only. So far, I have this attempt:
# /. (p_List /; Depth[p] == 2) :> (bar /@ p) & /@ foo
(* {1, {bar[2], bar[3]}, {4, 5, {bar[6], bar[7]}}, {bar[8]}, {bar[9]}} *)
As you can see, pattern matching looks at ALL lists, so I can't really use what I have. I suspect there could be some better, more functional solution to this (possibly using Scan, Reap, and Sow)?