3
$\begingroup$

I want to map a function on each element at the "deepest" level of a list.

The list can have an arbitrary number of dimensions.

The function needs the indices of the element to which it is being mapped.

How can I determine the indices of an element during mapping ?

$\endgroup$
3
  • 3
    $\begingroup$ for example?${}$ $\endgroup$ Aug 16 '19 at 13:28
  • 1
    $\begingroup$ does Map[MapIndexed[foo, #] &, list, {-2}] or MapIndexed[foo, list, {Depth[list] - 1}] give what you need? $\endgroup$
    – kglr
    Aug 16 '19 at 13:34
  • 1
    $\begingroup$ Yes, MapIndexed provides exactly what I need. Thanks AFT. $\endgroup$
    – Charlie
    Aug 16 '19 at 13:44
4
$\begingroup$

Use MapIndexed:

list = {a, {{b, c}, {d, e}}};

MapIndexed[foo, list, {Depth[list] - 1}]

{a, {{foo[b, {2, 1, 1}], foo[c, {2, 1, 2}]}, {foo[d, {2, 2, 1}], foo[e, {2, 2, 2}]}}}

$\endgroup$
0

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.