1
$\begingroup$

If I run the following code:

Do[
 Print["*** ", HoldForm[x] /. x -> a, " ***"];
 Print["Replace: ", (HoldForm[x] /. x -> a) /. {n1 -> 1, n2 -> 2, n3 -> 3}];
 Print["FullForm: ", FullForm[a]];
 , {a, {n1 n2, -n1 n2, n1 n2 n3}}
 ]

I get

    *** n1 n2 ***
    Replace: 1 x 2
    FullForm: Times[n1,n2]
    *** -n1 n2 ***
    Replace: -2
    FullForm: Times[-1,n1,n2]
    *** n1 n2 n3 ***
    Replace: 2 x 3
    FullForm: Times[n1,n2,n3]

I kind of understand what is going on, but I would like the output in the second case to be -1 x 2 and in the third case 1 x 2 x 3. How do I do that?

$\endgroup$
2
  • 3
    $\begingroup$ Because $1$ is an identity element for multiplication, it gets removed at once in Times[]. (Similarly, $0$ is quickly removed in Plus[].) Perhaps you want something like Inactivate[Times[1, 2, 3], Times]? $\endgroup$ May 14, 2020 at 15:31
  • $\begingroup$ Thank you. Unfortunately, I need to block 1, not Times, and Inactivate[1] is just the same as 1. However, your solution inspired me to find a solution of my own, which I will post now. $\endgroup$
    – Mattia
    May 14, 2020 at 19:26

1 Answer 1

2
$\begingroup$

It is enough to write the substitution rule as

{n1 -> HoldForm[1], n2 -> 2, n3 -> 3}

If later one wants the expression evaluated, it will be enough to use HoldForm[] twice.

$\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.