10
$\begingroup$

MapIndex returns the index in a list instead of as shown in my revised example. I can work with it (or work around it), but what's the design concept? It seems like an unnecessary complication, but I'm sure there is a reason I don't see.

enter image description here

I tagged this with a design-pattern tag. I'm not sure if that's appropriate. Editors please remove the tag if it's not.

$\endgroup$
4
  • 2
    $\begingroup$ I guess this is due to the fact that once you provide a levelspec, it becomes necessary, consider: MapIndexed[f, {{a, b}, {c, d, e}}, {2}] $\endgroup$ Commented Sep 17, 2013 at 18:30
  • $\begingroup$ In addition to what others said, one can remove this {} using First@ like this: MapIndexed[f[#1, First@#2] &, {a, b, c, d}] gives {f[a, 1], f[b, 2], f[c, 3], f[d, 4]} $\endgroup$
    – Nasser
    Commented Sep 17, 2013 at 18:33
  • $\begingroup$ @PinguinDirk I just looked at your example and see how it works. Level specifications are tricky: e.g. 2 vs {2}. I know how it works, but I try to stay on deck one. $\endgroup$ Commented Sep 17, 2013 at 18:44
  • $\begingroup$ Today's interest in expression diffs reminded me about my expression diff code, where there is an application of MapIndexed mapping on possibly deeply nested expression - there I used the second argument essentially as a unique Id for a part in an expression. $\endgroup$ Commented Sep 18, 2013 at 10:38

1 Answer 1

15
$\begingroup$

The "unnecessary" complication is needed for those cases where you specify deeper levels than the first:

MapIndexed[f, {{a}, {b}}, {2}]
(* {{f[a, {1, 1}]}, {f[b, {2, 1}]}} *)

The following code produces what you want:

myMapIndexed[f_, l_] := Inner[f, l, Range[Length[l]], List];
myMapIndexed[f, {a, b, c, d}]
(* {f[a, 1], f[b, 2], f[c, 3], f[d, 4]} *)
$\endgroup$
1
  • $\begingroup$ I get it. I haven't had an application with a nested structure come up in anything I've done. Thanks. $\endgroup$ Commented Sep 17, 2013 at 18:36

Your Answer

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

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