GeneralNew Command with one or two Arguments

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
gizzmo
Posts: 1
Joined: Wed May 09, 2012 2:35 am

New Command with one or two Arguments

Post by gizzmo »

Hi, I am trying to define a command that would take one or two arguments. One should be mandatory and the other one not. This is what I have right now

Code: Select all

\newcommand\braket[2][]{\langle\ifx\@empty#2#1\else#1\lvert#2\fi\rangle}
The desired behaviour is that:
  • \braket{a} gives me \langle a \rangle
  • \braket{a}{b} gives me \langle a | b \rangle
What am I doing wrong?
Last edited by Stefan Kottwitz on Wed May 09, 2012 8:59 am, edited 1 time in total.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

localghost
Site Moderator
Posts: 9202
Joined: Fri Feb 02, 2007 12:06 pm

New Command with one or two Arguments

Post by localghost »

There are two small details.
  1. The optional argument is always #1. You are testing argument #2 for \empty.
  2. The optional argument is always given in brackets to the command instead of braces.
This translated to your example gives the below line.

Code: Select all

\newcommand*{\braket}[2][]{\langle\ifx &#1& #2\else #2\lvert #1\fi\rangle}
Some useful explanations by cgnieder about the \ifx test can be found in another topic [1]. Application of the command is like this.

Code: Select all

$\braket[b]{a}$
It will result in ‹a|b›. For others it should be noted that this needs the amsmath package for the \lvert command.

Perhaps you are interested in the braket package. It offers similar structures to typeset such expressions.

[1] View topic: ifx and ifthenelse


Best regards and welcome to the board
Thorsten
User avatar
cgnieder
Site Moderator
Posts: 2000
Joined: Sat Apr 16, 2011 7:27 pm

New Command with one or two Arguments

Post by cgnieder »

If you want to stick with your original syntax you can use the xparse package:

Code: Select all

\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand\braket{mg}{%
  \langle #1%
    \IfNoValueF{#2}{\vert#2}%
  \rangle}

\begin{document}
 $\braket{a}$  $\braket{a}{b}$
\end{document}
Regards
site moderator & package author
Post Reply