# MakeBoxes for Power not matching when inside Times?

If I try to define boxes for Power[x,-1] like this,

MakeBoxes[Power[x, -1], TraditionalForm] := "matched";


it works as long as the coefficient is 1:

1/x // TraditionalForm


$\text{matched}$

But, for other coefficients it doesn't work, for example:

2/x // TraditionalForm


$\frac{2}{x}$

But why? After all, FullForm[2/x] returns Times[2,Power[x,-1]], which does contain Power[x,-1] for which the MakeBoxes definition was given. But why doesn't it work?

What is the proper way to define boxes for such expressions?

• For TraditionalForm[2/x], I expected "$2\,\text{matched}$" as the output. – QuantumDot Sep 3 '16 at 1:37

I believe the existing rules for Times take precedence. (i.e. act first.)

Perhaps a derivative of this can work for you:

MakeBoxes[x_ /; ! FreeQ[Unevaluated@x, Power], TraditionalForm] :=
ToBoxes[Unevaluated[x] /. _Power -> "matched"];


Responding to your entirely valid performance concern please test these for comparison:

MakeBoxes[x_Times /; ! FreeQ[Unevaluated@x, Power], TraditionalForm] :=
ToBoxes[Unevaluated[x] /. _Power -> "matched"];


Or:

MakeBoxes[a___ * x_Power * b___, TraditionalForm] := MakeBoxes[a * "matched" * b]

• Thanks. But your suggestion looks grotesquely inefficient. Would you know how to get it to work without using a Conditional on a "blanket" pattern? – QuantumDot Sep 3 '16 at 11:21
• @QuantumDot please see the update. – Mr.Wizard Sep 3 '16 at 11:54
• Thanks. Since Attributes[Times] = {Orderless, (*...*)}, you could simplify the lhs of your last example to MakeBoxes[a___ * x_Power, TraditionalForm] := (*...*), no? – QuantumDot Sep 4 '16 at 23:05

Inspired by Mr. Wizard's answers, here is another possibility:

MakeBoxes[c_. x_Power, TraditionalForm] := MakeBoxes[c "matched"]

• Very nice addition. :-) – Mr.Wizard Sep 5 '16 at 1:29