How to use the number of arguments in a macro?

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

enter image description here


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

enter image description here

Æ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} \,
}

enter image description here

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
}

enter image description here


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.

enter image description here

Tags:

Plain Tex