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


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

2/x // TraditionalForm


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?

  • $\begingroup$ For TraditionalForm[2/x], I expected "$2\,\text{matched}$" as the output. $\endgroup$ – 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"];


MakeBoxes[a___ * x_Power * b___, TraditionalForm] := MakeBoxes[a * "matched" * b]
  • $\begingroup$ Thanks. But your suggestion looks grotesquely inefficient. Would you know how to get it to work without using a Conditional on a "blanket" pattern? $\endgroup$ – QuantumDot Sep 3 '16 at 11:21
  • $\begingroup$ @QuantumDot please see the update. $\endgroup$ – Mr.Wizard Sep 3 '16 at 11:54
  • $\begingroup$ Thanks. Since Attributes[Times] = {Orderless, (*...*)}, you could simplify the lhs of your last example to MakeBoxes[a___ * x_Power, TraditionalForm] := (*...*), no? $\endgroup$ – 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"]
  • $\begingroup$ Very nice addition. :-) $\endgroup$ – Mr.Wizard Sep 5 '16 at 1:29

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.