0

I want to define a macro with an optional argument that will work with superscript and subscript in math mode. e.g. \binaryB{\alpha} will result into \mathbb{B}^{\alpha}() and \binaryB will result into simply \mathbb{B}().

I have defined my macro as follows: \newcommand*{\binaryB}[1][]{\mathbb{B}^{#1}}.

But unfortunately, the superscript does not work. It is showing as:

Is there anything I am missing here?

5
  • Try \binaryB[\alpha] ... The optional argument needs [] not {} ... You gave just a command without optional argument and \alpha comes just as a grouped \alpha ... not as a part of your commend
    – koleygr
    Mar 11, 2020 at 19:50
  • Thanks for your answer. I have tried that, and that works. I am looking for something that will use braces for nonempty argument. \binaryB{\alpha} or \binaryB. Does Latex understand that? Otherwise I have to change a whole bunch of lines in my document. Mar 11, 2020 at 20:00
  • It's possible to do, but not standard (TeX is Turing-complete so anything computable is possible). It would be a lot easier to just change your input.
    – Don Hosek
    Mar 11, 2020 at 20:06
  • 1
    What's the advantage of \binaryB{\alpha} over \binaryB^{\alpha}?
    – egreg
    Mar 11, 2020 at 20:16
  • @egreg Well, it can encapsulate the notation, so that if the author wants to change it at a later time (e.g., to a subscript instead), they can do so from a single control point. Dec 28, 2023 at 14:25

1 Answer 1

1
  • Practically, an optional argument delimited by { and } breaks the (la)tex conventions, hence is strongly not recommended.
  • Technically, the required syntax can be implemented as:
\documentclass{article}
\usepackage{amsfonts}

\makeatletter
\newcommand{\binaryB}{
  \mathbb{B}
  \@ifnextchar\bgroup{\sp}{}
}
\makeatother

\begin{document}
\[
  \binaryB \qquad \binaryB{\alpha}
\]
\end{document}

With xparse package, the same command can be defined as

\NewDocumentCommand \binaryB {g}
  {
    \mathbb{B}\IfValueT{#1}{\sp{#1}}
  }

Note that g-type argument is marked as deprecated.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .