5

I like to define a macro with an optional parameter. As an example, consider a macro for the differential:

\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{bm}

\newcommand\drm{\mathop{}\!\mathrm{d}}
\newcommand\Drm[1]{\mathop{}\!\mathrm{d^#1}}

\begin{document}

\begin{equation}
\int\limits_0^\infty \drm t \, f(t)
\end{equation}

\begin{equation}
\int\limits_0^\infty \Drm{3} r \, g(\bm{r})
\end{equation}

\end{document}

The macros for the differentials are taken from an earlier post. Apart from my own question, why is there a \mathop{} in the definition of the differentials? But second, how can I achieve a macro that puts both of them together? Like it is with \sqrt, where you can do \sqrt{x} or \sqrt[3]{x}. I like to do \drm or \drm[3].

DaPhil
  • 3,365

1 Answers1

13

Are you sure you want

\newcommand\Drm[1]{\mathop{}\!\mathrm{d^#1}}

rather than

\newcommand\Drm[1]{\mathop{}\!\mathrm{d}^{#1}}

which would be rather more usual I think (It makes no difference if the superscript is a digit but try n) and you certainly need the {} around #1 if there might be two digits.

To make the argument optional you could use

 \newcommand\Drm[1][]{\mathop{}\!\mathrm{d}^{#1}}

But that makes ^{} in the empty case which can affect spacing so better is

 \newcommand\Drm[1][\relax]{%
   \mathop{}\!\mathrm{d}\ifx\relax#1\relax\else^{#1}\fi}

where you omit the superscript in the default case.

David Carlisle
  • 757,742