TransWikia.com

Defining a new command using a conditional

TeX - LaTeX Asked by sixtyTonneAngel on November 6, 2021

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

No packages required.

documentclass{article}
newcommandF[1]{Faux#1endFaux}
makeatletter
newcommandFaux{@ifnextchar(FnoaddFadd}
makeatother
defFadd#1endFaux{F(#1)}
defFnoadd#1endFaux{F#1}
begin{document}
$F{(x)}$ $F{(G(x))}$

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

enter image description here

Answered by Steven B. Segletes on November 6, 2021

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.

Answered by G. de Man on November 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP