2
$\begingroup$

Several operations require you to map over a list of values and to know the index of each value as you process it. To accomplish this, my current somewhat ugly solution uses MapThread:

MapThread[#1 (1 + 0.15)^(-#2) &, {{-42000, 32400, 33400, 32500, 32500, 33000}, Range@6}]

This lets me pull the index out as the second parameter in my function. It works, but it has annoying requirement of manually updating the parameter on Range to match the length of the list you want to process.

Is there a better way to get the index of a list element while processing it with a map?

$\endgroup$

1 Answer 1

4
$\begingroup$

The built-in function MapIndexed provides this functionality in a cleaner fashion. It automatically passes the index of a list element along with the element itself into the mapping function. By using MapIndexed the example provided in the question can be simplified as so:

MapIndexed[#1 (1 + 0.15)^(-First@#2) &, {-42000, 32400, 33400, 32500, 32500, 33000}]

The First call is required because MapIndexed wraps the indexes it provides in a one-element array.

$\endgroup$
1
  • 1
    $\begingroup$ one more ugly exemplar: #1 (1 + 0.15)^(-#2) & @@@ Transpose[{list, Range@Length@list}] $\endgroup$
    – garej
    Mar 9, 2016 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.