# Replace rules change dimension

This is absolutely driving me crazy, I don't know if this is a bug or what, but replace rule sometimes change dimension of my data.

Say I have data:

FLIST={{1,1,1}, {2,2,2}};


and replace rule:

ReplaceShit = {
A->FLIST[[2]],
B->FLIST[[1]]
};


It seems to work fine:

(A - B) /. ReplaceShit
{1, 1, 1}


However, when I use it in this way it gives different answer:

(FLIST[[2]] - B) /. ReplaceShit
{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}}


• Look at what happens when you evaluate, say {2,2,2} - B on its own. – High Performance Mark Jul 5 at 16:02
• Use Trace to see why. (FLIST[[2]] - B) is first evaluated to ({2, 2, 2} - B), i.e., ({2 - B, 2 - B, 2 - B} prior to the replacement. The subsequent replacement produces a 3x3 matrix. – Bob Hanlon Jul 5 at 16:12

So, what's happening? First, let's establish that ReplaceAll (/.) does not have any Hold* attributes (not HoldAll and not HoldFirst.)

Attributes[ReplaceAll]


{Protected}

Then let's write the expression in its FullForm:

list = {{1, 1, 1}, {2, 2, 2}};
replaceIt = {
A -> {1, 1, 1},
B -> {2, 2, 2}
};

ReplaceAll[list[[1]] - B, replaceIt]


Now, since ReplaceAll does not have any Hold* attribute, arguments will be evaluated before being passed to the function. Let's evaluate the arguments. Take them one by one and evaluate them in separate cells.

The first argument evaluates like this:

list[[1]] - B


{1 - B, 1 - B, 1 - B}

The second argument evaluates in an obvious way. In conclusion, we now have the following expression:

ReplaceAll[
{1 - B, 1 - B, 1 - B}, {
A -> {1, 1, 1},
B -> {2, 2, 2}
}]


This is what gets evaluated, and you can probably see from this why you are getting the result that you're getting.

I found the solution, I get the desired result by using Unevaluated function as:

Unevaluated[(FLIST[[2]] - B)] /. ReplaceShit