[Tex/LaTex] newcommand with variable number of arguments

conditionalsmacrosparameters

I have seen several related questions, but none seems to address specifically this.

I would like to define a command that accepts a variable number of arguments. Something like

\newcommand{\func}(1){\if{#1}{f(#1)}{f}}

So that if there is a parameter the output will be f(#1) and if there is no parameter the output will be f, and never f().

Is this possible?

Best Answer

The xparse package allows for some really cool syntax stuff.

\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand\funcF{d()}{%
  \IfValueTF{#1}{f(#1)}{f}}

% This is a version that follows more popular LaTeX syntax conventions.
\NewDocumentCommand\NormalFuncF{o}{%
  \IfValueTF{#1}{f(#1)}{f}}

\begin{document}
\[ \funcF(2) = 4       \]
\[ \funcF              \]
\[ \NormalFuncF[2] = 4 \]
\[ \NormalFuncF        \]
\end{document}

output