# How to use the number of arguments in a macro?

I want to use a conditionally have a command produce two types of output in plain tex. I want to show a fraction style derivative with one mandatory option to give the independent variable, and a second, optional argument to provide a power, to be displayed for a 2nd, 3rd,..., nth derivate.

What I do have so far is the following.

\def\dv#1{{d \over d #1}}

\def\dv#1#2{{d^{#2} \over d #1^{#2}}}


I would like to create a macro that does both of these at once, depending on the number of arguments given. How can I access the number of arguments passed to tex by the macro and implement the combined macro?

• The standard TeX way of providing optionality of arguments is with the use of some sort of delimiter as part of the definition. Otherwise, TeX has no way of deciding that \dv a2 may sometimes mean for the 2 to be an optional argument and other times not. – Steven B. Segletes Mar 1 at 3:55
• If this is a learning exercise, then great, but if this is for publication then you might be better off using a package. There are several to typeset calculus, and for LaTeX there is the dv command from the physics package, although the package is somewhat polarising. Also, the "d" should be typeset in upright roman. – oliversm Mar 1 at 16:07

Welcome! If you are willing to slightly change the syntax, it is easy.

\def\dv#1#2;{{d^{#2} \over d #1^{#2}}}
$\dv{a};$ $\dv{a}2;$ $\dv a;$ $\dv a2;$

\bye


With a LaTeX-style optional argument except that, for the sake of simplicity, we don't attempt to skip spaces before the opening bracket (if you want to tolerate spaces there, just copy LaTeX's \@ifnextchar):

\catcode\@=11

\def\dv{\futurelet\next\@dv}

\def\@dv{%
\ifx\next [%
\expandafter\@dvWithOptArg
\else
\expandafter\@dvWithoutOptArg
\fi
}

\def\@dvWithOptArg[#1]#2{%
{d^{#1} \over d #2^{#1}}%
}

\def\@dvWithoutOptArg#1{%
{d \over d #1}%
}
\catcode\@=12

$\dv{x} x^3 = 3x^2$\qquad $\dv[2]{x} x^3 = 6x$\qquad $\dv[3]{x} x^3 = 6$\qquad
$\dv[4]{x} x^3 = 0$

\bye


# Æsthetic considerations

You may want to add some spacing after d/dx & friends:

\def\@dvWithOptArg[#1]#2{%
{d^{#1} \over d #2^{#1}} \,
}

\def\@dvWithoutOptArg#1{%
{d \over d #1} \,
}


What precedes added a \thinmuskip, i.e. 3mu in plain TeX. The following adds a slightly smaller space (2mu):

\def\@dvWithOptArg[#1]#2{%
{d^{#1} \over d #2^{#1}} \mskip 2mu\relax
}

\def\@dvWithoutOptArg#1{%
{d \over d #1} \mskip 2mu\relax
}


You can use a more “plain TeX” style like \root...\of

\def\dv#1\v#2{%
\if\relax#1\relax
\let\next\relax
\else
\def\next{^{#1}}
\fi
{d\next\over d#2\next}%
}

$$\dv\v x x^3=3x^2\qquad \dv2\v x x^3=6x\qquad \dv3\v x x^3=6$$

\bye


The check for emptiness of the first argument is very important, because x^{} adds \scriptspace.