4
$\begingroup$

The very last example in the documentation for MapAt is:

MapAt applies f repeatedly if a part is mentioned repeatedly:

In[1]:= MapAt[f, {a, b, c, d}, {{1}, {3}, {1}}]

Out[1]= {f[f[a]], b, f[c], d}

So f is applied twice to the first element.

I have a problem in which f takes an additional arguments which should be different in the first and second invocations. Any ideas on how to do this?

If a MapAtIndexed function existed, I could do something like this:

d = {{1, "x"}, {3, "w"}, {1, "q"}};

MapAtIndexed[f[#, Extract[d, #2]] &, {a, b, c, d}, List /@ First /@ d]

And the output would be:

{f[f[a, "x"], "q"], b, f[c, "w"], d}
$\endgroup$
4
$\begingroup$
list = {a, b, c, d};
app = {{1, "x"}, {3, "w"}, {1, "q"}};
Fold[MapAt[f[#, u] & /. u -> #2[[2]], #1, #2[[1]]] &, list, app]

(* {f[f[a, "x"], "q"], b, f[c, "w"], d}*)

Or perhaps:

r = list
(r[[#1]] = f[r[[#1]], #2]) & @@@ app; r
(* {f[f[a, "x"], "q"], b, f[c, "w"], d} *)
$\endgroup$
  • $\begingroup$ @gus muchas de nadas :) $\endgroup$ – Dr. belisarius Mar 2 '15 at 12:22

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.