我可以将 \newcommand 命令与其自身嵌套吗?

我可以将 \newcommand 命令与其自身嵌套吗?

目前,我想定义一个命令,使我能够轻松地在集合论中写出集合的常用符号。使用该\newcommand命令,我能够定义以下内容:

\documentclass{article}
\usepackage{ifthen}
\usepackage{calc}
\usepackage{amsmath,amssymb,mathtools}
\usepackage{xcolor}

\newcommand{\TCConjunto}[2]{%
\ifthenelse{\equal{#1}{}\AND\equal{#2}{}}%
{\varnothing}%
{\ifthenelse{\equal{#1}{}}%
{\{#2\}}%
{\ifthenelse{\equal{#2}{}}%
{\{#1\}}%
{\{#1\,:\,#2\}}%
}%
}%
}%

%%-----

\newcommand{\TCUnion}[2]{%
\ifthenelse{\equal{#1}{}\AND\equal{#2}{}}%
{\varnothing}%
{\ifthenelse{\equal{#1}{}}%
{#2}%
{\ifthenelse{\equal{#2}{}}%
{#1}%
{#1\cup #2}%
}%
}%
}%

\begin{document}

\section{Introduction}

$\TCConjunto{}{}$

$\TCConjunto{A,B,C}{}$

$\TCConjunto{}{A,B,C}$

$\TCUnion{}{}$

$\TCUnion{A}{}$

$\TCUnion{}{B}$

$\TCUnion{A}{B}$

%%%%%%$\TCUnion{A}{\TCUnion{B}{C}}$

\end{document}

我刚才提到的命令使用“简单”参数。在一行代码中,我使用符号%来突出显示问题;当我尝试将其中一个命令嵌套在自身中时,它会引发错误。你能帮我找出问题所在吗?

答案1

我从未使用过该ifthen软件包,但我偏爱使用纯 TeX 条件。有了这些条件,您可以随意\TCConjunto嵌套。\TCUnion

下面显示的是 LaTeX 代码输出的屏幕截图。

\documentclass{article}
\usepackage{amssymb}

\newcommand{\TCConjunto}[2]{
  \if\relax\detokenize{#1}\relax
    \if\relax\detokenize{#2}\relax
      \varnothing%
    \else
      \{#2\}%
    \fi
  \else
    \if\relax\detokenize{#2}\relax
      \{#1\}%
    \else
      \{#1\,:\,#2\}%
    \fi
  \fi
}

%%-----

\newcommand{\TCUnion}[2]{
  \if\relax\detokenize{#1}\relax
    \if\relax\detokenize{#2}\relax
      \varnothing%
    \else
      #2%
    \fi
  \else
    \if\relax\detokenize{#2}\relax
      #1%
    \else
      #1\cup#2%
    \fi
  \fi
}

\begin{document}

\section{Introduction}

\setlength{\parindent}{0pt} % to make the screenshot look prettier

$\TCConjunto{}{}$

$\TCConjunto{A,B,C}{}$

$\TCConjunto{}{A,B,C}$

$\TCConjunto{A}{B}$

$\TCUnion{}{}$

$\TCUnion{A}{}$

$\TCUnion{}{B}$

$\TCUnion{A}{B}$

$\TCUnion{\TCUnion{A}{\TCUnion{B}{\TCConjunto{C}{D}}}}{E}$

\end{document}

答案2

如果改变语法还不算太晚,我主张一个可选的论点\TCConjunto

\documentclass{article}
\usepackage{amsmath}

\NewDocumentCommand{\TCConjunto}{om}{%
  \IfNoValueTF{#1}{%
    \IfBlankTF{#2}{\emptyset}{\{#2\}}
  }{\{#1:#2\}}%
}

\NewDocumentCommand{\TCUnion}{mm}{%
  \IfBlankTF{#1}{%
    \IfBlankTF{#2}{\emptyset}{#2}%
  }{%
    \IfBlankTF{#2}{#1}{#1\cup#2}%
  }%
}

\begin{document}

$\TCConjunto{}$

$\TCConjunto{A,B,C}$

$\TCConjunto[x]{x\notin x}$

$\TCUnion{}{}$

$\TCUnion{A}{}$

$\TCUnion{}{B}$

$\TCUnion{A}{B}$

$\TCUnion{A}{\TCUnion{B}{C}}$

\end{document}

抱歉,但是当我看到用于空集\emptyset的管道工符号时,我的眼睛都红了。\varnothing

相关内容