1

I want to define a new command (to be used only in mathmode), the execution of which depends on the input given to it. Particularly, I want to define \F as

\newcommand{\F}[1]{F#1}

if the first character in its input is ( , and as

\newcommand{\F}[1]{F(#1)}

if the first character in its input is not ( .

As an example, I would like \F{x} to output F(x) and \F{(x)} to output F(x).

I have no idea how to go about this.

2 Answers 2

2

No packages required.

\documentclass{article}
\newcommand\F[1]{\Faux#1\endFaux}
\makeatletter
\newcommand\Faux{\@ifnextchar(\Fnoadd\Fadd}
\makeatother
\def\Fadd#1\endFaux{F(#1)}
\def\Fnoadd#1\endFaux{F#1}
\begin{document}
$\F{(x)}$ $\F{(G(x))}$

$\F{x}$ $\F{G(x)}$ 
\end{document}

enter image description here

1

You can achieve this using the following code:

\usepackage{xstring}
\usepackage{ifthen}
\newcommand{\F}[1]{
    \StrLeft{#1}{1}[\firstletter]%
    \StrRight{#1}{1}[\lastletter]%
    \ifthenelse{\equal{(}{\firstletter} \AND \equal{)}{\lastletter}}{F#1}{F(#1)}%
}

It basically checks what the first and last characters of the argument are, and if those are '(' and ')', it will output the argument without extra parentheses.

1
  • Since I cannot accept two answers, I've upvoted your answer. I accepted the other answer since it doesn't require a package. Thank you though. Jul 21, 2020 at 16:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .