6

I want to define a new command such that when a first and only argument is given it does one thing and when a second argument is given it expands the first argument. The idea is to replicate the probability function. One argument is for probability distribution and two arguments are for conditional probability distribution. I really don't know how to do it.

The (completed) following code

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amssymb}

\newcommand{\PP}[2]{???}

\begin{document}

$\PP{X}$

$\PP{X}{Y}$

\end{document}

should print

\mathbb{P}{\left({X}\right)}
\mathbb{P}{\left({X}\middle|{Y}\right)}

I wouldn't like to have an optional argument because it would affect the order and readability of the code. I mean, I prefer \PP{X}{Y} over \PP[Y][X].

Could you please help me?

Thanks

Camilo
  • 71

3 Answers3

9

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.

egreg
  • 1,121,712
7

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

2

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