My goal is to apply MapIndexed
to every element of a nested list without destroying the arithmetic operations within the elements. For example, let's start with this list:
{a, {b, {c^d, {e + f g}}}}
This is what I want achieved using MapIndexed
and applying a function h
(this was explicitly typed out, so the bracket placement might be wrong, but you get the idea):
{h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2, 1}]}}}}
My (failed) attempts
1) Of course the {-1}
levelspec of MapIndexed
was way too aggressive:
MapIndexed[h, {a, {b, {c^d, {e + f g}}}}, {-1}]
2) This also did not work:
Function[l, MapIndexed[h, l], Listable]@{a, {b, {c^d, {e + f g}}}}
To see why, MapIndexed
is nested in a Defer
:
Function[l, Defer@MapIndexed[h, l], Listable]@{a, {b, {c^d, {e + f g}}}}
It's clear that MapIndexed
is threaded over the list first before it evaluated, while what I want is for MapIndexed
to be applied to the whole list, and only the evaluation thereafter will be listable (I hope the distinction is clear).
My question is: How can I make my MapIndexed
listable as seen in the desired output? Solutions without using MapIndexed
are also appreciated.
{a, {b, {c^d, {e + f g}}}} -> {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2, 1}]}}}}
h[a, {1}]
andh[b, {2, 1}]
, but then on deeper levels you have e.g.h[c^d], {2, 2, 1}
instead ofh[c^d, {2, 2, 1}]
as I would expect from how your pattern begins. Explanation? $\endgroup$