3
$\begingroup$

Suppose that I want to typeset an object such that it looks differently for different powers. The simplest example would be a three vector. For odd powers I want it to look like $$|\vec{v}|^n,$$ while for even powers it should be just $$\vec{v}^n.$$

The naive approach

myvec /: MakeBoxes[myvec[x_], TraditionalForm] := 
 RowBox[{"|", OverscriptBox[ToBoxes[x], "\[RightArrow]"], "|"}]
myvec /: MakeBoxes[myvec[x_]^n_, TraditionalForm] := 
 SuperscriptBox[
   RowBox[{"|", OverscriptBox[ToBoxes[x], "\[RightArrow]"], "|"}], 
   ToBoxes[n]] /; OddQ[n]
myvec /: MakeBoxes[myvec[x_]^n_, TraditionalForm] := 
 SuperscriptBox[OverscriptBox[ToBoxes[x], "\[RightArrow]"], 
   ToBoxes[n]] /; EvenQ[n]

obviously doesn't work, because the tag is too deep. A "dirty" hack is to use

Unprotect[Power];
myvec /: MakeBoxes[myvec[x_], TraditionalForm] := 
  RowBox[{"|", OverscriptBox[ToBoxes[x], "\[RightArrow]"], "|"}];
Power /: MakeBoxes[Power[myvec[x_], n_], TraditionalForm] := 
  SuperscriptBox[
    RowBox[{"|", OverscriptBox[ToBoxes[x], "\[RightArrow]"], "|"}], 
    ToBoxes[n]] /; OddQ[n];
Power /: MakeBoxes[Power[myvec[x_], n_], TraditionalForm] := 
  SuperscriptBox[OverscriptBox[ToBoxes[x], "\[RightArrow]"], 
    ToBoxes[n]] /; EvenQ[n];
Protect[Power];

This works fine but involves redefining protected functions, which is something I'd really like to avoid. So, is there a safer and more elegant way to achieve the desired result?

$\endgroup$
5
$\begingroup$

Tags (e.g. Power /:) are not necessary here. So

MakeBoxes[myvec[x_], TraditionalForm] := 
  TemplateBox[{OverscriptBox[ToBoxes[x], "→"]}, "Abs"];
MakeBoxes[Power[myvec[x_], n_], TraditionalForm] := 
  SuperscriptBox[
    TemplateBox[{OverscriptBox[ToBoxes[x], "→"]}, "Abs"], 
    ToBoxes[n]] /; OddQ[n];
MakeBoxes[Power[myvec[x_], n_], TraditionalForm] := 
  SuperscriptBox[OverscriptBox[ToBoxes[x], "→"], 
    ToBoxes[n]] /; EvenQ[n];

myvec[v] + myvec[v]^2 + myvec[v]^3 // TraditionalForm

$ \left| \vec{v}\right| ^3+\left| \vec{v}\right| +\vec{v}^2 $

Here I use TemplateBox[{...}, "Abs"] to omit additional parentheses (see here). If you are interested in TeXForm and get redundant \left\left and \right\right see here.

$\endgroup$
  • $\begingroup$ Thanks! It looks like one actually never (or almost never) needs tags for typesetting, right? $\endgroup$ – vsht Feb 1 '15 at 22:20
  • $\begingroup$ @vsht It is good idea to use tags when you can. For example, it helps you to clear certain definitions with ClearAll[yourTag]. $\endgroup$ – ybeltukov Feb 2 '15 at 1:08

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.