1
$\begingroup$

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}}

I have absolutely no idea why this became 3x3 matrix instead 1x3 vector. Please help.

$\endgroup$
  • 1
    $\begingroup$ Look at what happens when you evaluate, say {2,2,2} - B on its own. $\endgroup$ – High Performance Mark Jul 5 at 16:02
  • 1
    $\begingroup$ 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. $\endgroup$ – Bob Hanlon Jul 5 at 16:12
2
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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

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

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.