6

I want to define a macro, call it \func, so that \func will output\phi, and \func[i] will output \phi(i).

what is the easiest way to achieve this?

I know there are other questions that address this issue - I guess one of them is exactly my question and I just don't get it :)

olamundo
  • 463

2 Answers2

8

You can define \func to take an optional argument:

\documentclass{article}

\newcommand\func[1][]{\phi\ifx\\#1\\\else(#1)\fi}

\begin{document}

$\func\quad\func[i]$

\end{document}

enter image description here

egreg
  • 1,121,712
Gonzalo Medina
  • 505,128
  • Thanks! But this just exploits the fact that \phi_{} looks the same as \phi, right? I need a slightly more general solution. I will edit my question to prevent this "loop hole" :) – olamundo Nov 03 '12 at 15:37
  • @Qrrbrbirlbel right; will do so. – Gonzalo Medina Nov 03 '12 at 15:38
  • @noam please see my updated answer. Is this what you want? – Gonzalo Medina Nov 03 '12 at 15:45
  • 1
    @GonzaloMedina A subscript (even if it's empty) adds a small space after the symbol; its size is in the parameter \scriptspace, default value 0.5pt. I've also put a better test in the conditional. – egreg Nov 03 '12 at 15:48
8

xparse-based solution

\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\func}{o}{%
  \phi
  \IfNoValueF{#1}{(#1)}%
}

\begin{document}

$\func\quad\func[i]$

\end{document}

where you want a single optional ('o-type') argument.

Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036