3
$\begingroup$

Consider

expr = Hold[1 + a + x + b + c + y + z];
idxes = {{1, 3}, {1, 4}};

Q1. I don't understand why

MapAt[Framed, expr, idxes]

works, but

MapAt[(Framed[#]) &, expr, idxes]

does not. Is there a problem with using pure functions with MapAt? Or is it Hold that causes troubles?

Q2. More in general, I would like to pass the position n in MapAt also as a parameter inside f. More precisely, in the following MWE consider how to rewrite the last line

expr = Hold[1 + a + x + b + c + y + z];
idxes = {{1, 3}, {1, 4}};
color = {{RGBColor[1, 0, 0], RGBColor[0, 1, 0], RGBColor[0, 0, 1], RGBColor[1, 1, 0]}};
tmp = MapAt[Framed, expr, idxes];
tmp /. Framed[p_] :> EventHandler[Framed[p], "MouseDown" :> (CurrentValue[EvaluationCell[], Background] = Extract[color, Position[tmp, Framed[p]]][[1]])]

avoiding to having to re-evaluate Position[tmp, Framed[p]], which actually gives the position previously specified in idxes. I thought something like

MapAt[(EventHandler[Framed[#], "MouseDown" :> (CurrentValue[EvaluationCell[], Background] = Extract[color, #][[1]])])& , expr, idxes]

worked, but it does not.

$\endgroup$

1 Answer 1

3
$\begingroup$

There are a couple of different questions here.

  1. The two function forms

MapAt[Framed, expr, idxes] and MapAt[(Framed[#]) &, expr, idxes] both work. But once they're applied via MapAt, we still have a Hold expression, so no further evaluation takes place. If you were to ReleaseHold at this point, you'd see that the both evaluate to the same result.

I think you might want to be doing this with Inactive instead of Hold. So, start with this instead:

expr = Inactivate[1 + a + x + b + c + y + z]

You get a couple of benefits. It's only the Plus that will be inactive, so your functions will evaluate regardless of which form you use. Second, you can just index into the expression as you would as if there were no wrapper. That is, right now you need to go down an extra layer to get past the Hold, but you don't have to bother with that when you use Inactive.

  1. Avoiding the position re-evaluation

Since the function you supply to MapAt is just going to be applied where you tell it, it won't have knowledge of the position itself. You're probalby going to need to wrap this in a larger function that first finds the positions and then later uses those positions to choose color.

$\endgroup$

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.