Newcommand with single and double argument (probability function)

You can do better, with a much easier user syntax.

\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\PP}{ s O{} >{\SplitArgument{1}{|}}m }
 {
  \mathbb{P}
  \IfBooleanTF{#1}
   { \PPauto #3 }
   { \PPfixed {#2} #3 }
 }

\NewDocumentCommand{\PPauto}{mm}
 {
  \left(
  \IfNoValueTF{#2} { #1 } { #1 \;\middle|\; #2 }
  \right)
 }

\NewDocumentCommand{\PPfixed}{mmm}
 {
  \mathopen{#1(}
  \IfNoValueTF{#3} { #2 } { #2 \mathrel{#1|} #3 }
  \mathclose{#1)}
 }

\ExplSyntaxOff

\begin{document}

\[
\PP{X} \quad \PP[\big]{X} \quad \PP*{\frac{X}{2}}
\]
\[
\PP{X|Y} \quad \PP[\big]{X | Y} \quad \PP*{\frac{X}{2} | Y}
\]

\end{document}

enter image description here

The command \PP has an optional argument for the size (never rely on \left and \right alone) or a * variant for the automatic sizing (use it only if really necessary).

The mandatory argument is split at |, if present. So the input code is much easier to read. Spaces around | are irrelevant.


I propose a syntax that uses a single argument only. EDITED to include Mico's spacing suggestion.

\documentclass{article}
\usepackage{listofitems,amssymb}
\newcommand\PP[1]{%
  \readlist\arglist{#1}
  \ifnum1=\arglistlen\relax
    \mathbb{P}{\left(#1\right)}
  \else
    \mathbb{P}{\left(\arglist[1]\;\middle|\;\arglist[2]\right)}
  \fi
}
\begin{document}
$\PP{X}$

$\PP{X,Y}$
\end{document}

enter image description here


Inspired of Werner's Answer and similar to Segletes's answer above:

\documentclass{article}
\usepackage{amssymb}
\newcommand{\pp}[1]{\ppaux#1\relax}
\def\ppaux#1#2\relax{%
  \ifnum\pdfstrcmp{#2}{}=0
      \mathbb{P}{\left(#1\right)}
  \else
    \mathbb{P}{\left(#1 \;\middle|\; #2\right)}
  \fi
}

\begin{document}

$\pp{X}$

$\pp{XY}$

$\pp{{XY}}$

\end{document}

enter image description here

Tags:

Arguments