[comp.text.tex] Optional arguments?

mathas_a@maths.su.oz.au ( Andrew ) (06/11/90)

Does anyone know of a way to define macros with an optional
argument in LaTeX. I know that you can fudge it as follows:
    
    \newcounter{Code}
    \newenvironment{code}[2]%
        {\refstepcounter{Code}%   
         \if#2N{}\else\label{#2}\fi% <- if second argument is
                                   %    an "N" don't label
         \def\CAPTION{#1}\begin{verbatim}}%
        {\centerline{Code fragment \theCode.\quad\CAPTION}}

(this is an improved version of my suggestion for the Code 
environment - it allows easy labelling of each fragment -
see previous posting if interested). 

However, it would be nicer to be able to do something like
    \newcommand\fred[2][1]{...}
and make fred have two mandatory arguments and one optional;
and \fred would be used in the normal way of
\fred{213}{lkjhksdfa}[hjd] etc.

Any ideas? Will post a summary if something turns up.

Andrew              - smile at a stranger today and help make
                      the world a better place. while you're,
                            at it, why not hug a friend!

duchier@cs.yale.edu (Denys Duchier) (06/12/90)

The code for LaTeX has numerous example of this. Say you want to
create a macro of no mandatory argument and 1 optional argument:

\def\foo{\@ifnextchar[{\@foo}{\@foo[DEFAULT]}}
\def\@foo[#1]{...}

the real work is done by \@foo. \foo simply checks the next character,
and if it isn't [ (indicating the presence of an optional argument), a
default optional argument is inserted ([DEFAULT] here).

Suppose you want a macro of 2 mandatory arguments and 1 optional
argument, which typesets in math mode the 1st mandatory argument
followed by the optional argument followed by the second mandatory
argument. The default argument should default to an arrow. Here is
what you do:

\def\sequent#1#2{\@ifnextchar[{\@sequent{#1}{#2}}{\@sequent{#1}{#2}[\Rightarrow]}}
\def\@sequent#1#2[#3]{\ifmmode#1#3#2\else$#1#3#2$\fi}

Note that the code in the above assumes that @ is considered a letter:
either put the code in a .sty file or bracket it with \makeatletter
\makeatother, or something...

--Denys