Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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 :)

share|improve this question
3  
Classic LaTeX way uses \func and \func[i] (note [...] instead of {...}). –  Paul Gaborit Nov 3 '12 at 15:33
    
@PaulGaborit - Thanks, I am quite new to latex :) Will change my question –  olamundo Nov 3 '12 at 15:34
    
@PaulGaborit - BTW, can you refer me to an explanation as to when should one use curly braces and when to use square braces? in this example they use curly braces: math.tamu.edu/~boas/courses/math696/math-macros.html –  olamundo Nov 3 '12 at 15:48
3  
    
@noam LaTeX uses [] to delimit the optional argument (always the first) of a command. All other arguments use curly braces. –  Paul Gaborit Nov 3 '12 at 15:53
add comment

2 Answers

up vote 7 down vote accepted

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

share|improve this answer
    
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 3 '12 at 15:37
    
@Qrrbrbirlbel right; will do so. –  Gonzalo Medina Nov 3 '12 at 15:38
    
@noam please see my updated answer. Is this what you want? –  Gonzalo Medina Nov 3 '12 at 15:45
    
yes! thank you very much! :) –  olamundo Nov 3 '12 at 15:47
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 3 '12 at 15:48
show 1 more comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.