# Newcommand with single and double argument (probability function)

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].

Thanks

New contributor
Camilo is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• How about a syntax like \PP{X,Y}, so that you would only ever need a single argument? – Steven B. Segletes Sep 15 at 19:43
• A different possibility would be to have \PP[X]{Y}. Then you'd just need to check if the optional value is empty or not. – Teepeemm Sep 15 at 19:48

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}


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]{%
\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}


• +1. I'd replace \middle| with \;\middle|\;, though. – Mico Sep 15 at 20:07

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