為清單中的每個元素公開一個新命令

為清單中的每個元素公開一個新命令

我有一個宏,使用套件中lVars定義(foreachpgffor前列腺素生長因子) 作為:

\newcommand{\lVars}[1]{\foreach \x [count=\ii] in {#1}{
  \ifnum\ii=1{} \else {,} \fi \lVar[\x]}
}

預期用途是這樣的術語\exists \lVars{a, b, c, d},它產生結果\exists \lVar[a], \lVar[b], \lVar[c], \lVar[d]。該命令\lVar[a]是另一個形式的自訂命令\newcommand{\lVar}[1][x]{\textsc{#1}},但很快可能會變得更加複雜。然後我\lVar在更大的論壇中使用新量化的元素。

然而,我卻極度懶惰。我非常希望這個巨集將每個清單元素公開為形式的新命令\lA\lB等等,它們本身擴展到實際的基礎\lVar[A]\lVar[B]......這些新命令將使我的公式符號顯著不那麼冗長。這些新指令應該持續到下一次ab,...在巨集的列表參數中使用lVars。所以,整體使用情況會是這樣的:

\begin{displaymath}
  \begin{array}{l}
    \exists \lVars{a, b, c}.~ \lA = \lB \implies \lA = \lC \\
    \lC = 0 \implies \lA = 0
    \exists \lVars{a, b}.~ \lA \neq \lB
  \end{array}
\end{displaymath}

And, as we see in the term $\lA = \lB$, the implication...

\newcommand我已經在 的主體上和\def主體內嘗試了各種排列foreach,但沒有任何運氣。有什麼建議或技巧嗎?

答案1

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\lVars}{m}
 {
  % cycle through the argument
  \clist_map_inline:nn { #1 }
   {
    % print the variable
    \lVar[##1]
    % if the variable is a, define \lA
    \tl_to_uppercase:n
     {
      \cs_gset_protected:cpn { \c_wright_prefix_tl ##1 }
     }
     { \lVar[##1] }
   }
 }
% We need to store the `l' prefix in a control sequence to hide it from \uppercase
\tl_const:Nn \c_wright_prefix_tl { l }
\ExplSyntaxOff

\newcommand{\lVar}[1][x]{\textsc{#1}}

\begin{document}
\begin{displaymath}
  \begin{array}{l}
    \exists \lVars{a, b, c}.~ \lA = \lB \implies \lA = \lC \\
    \lC = 0 \implies \lA = 0
    \exists \lVars{a, b}.~ \lA \neq \lB
  \end{array}
\end{displaymath}

And, as we see in the term $\lA = \lB$, the implication...
\end{document}

\lC然而, 「將永遠存在」的定義;如果您打算在不同的儲存格中使用它,則array需要全域定義。

在此輸入影像描述


\lFoo接受多字母變數並定義自的版本\lVars{foo}

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\lVars}{m}
 {
  % cycle through the argument
  \clist_map_inline:nn { #1 }
   {
    % print the variable
    \lVar[##1]
    % build the name with the first letter uppercase
    \wright_make_var_name:n { ##1 }
    \cs_gset_protected:cpn { \l__wright_var_name_tl } { \lVar[##1] }
   }
 }
\tl_const:Nn \c_wright_prefix_tl { l }
\cs_new:Npn \wright_make_var_name:n #1
 {
  % get the first letter and uppercase it
  \tl_to_uppercase:n
   {
    \tl_set:Nx \l__wright_var_name_tl { \tl_head:n {#1} }
   }
  % add the rest
  \tl_put_right:Nx \l__wright_var_name_tl { \tl_tail:n {#1} }
  % add the prefix
  \tl_put_left:Nx \l__wright_var_name_tl { \c_wright_prefix_tl }
 }
\ExplSyntaxOff
\newcommand{\lVar}[1][x]{\textsc{#1}}

\begin{document}
\begin{displaymath}
  \begin{array}{l}
    \exists \lVars{a, b, c}.~ \lA = \lB \implies \lA = \lC \\
    \lC = 0 \implies \lA = 0
    \exists \lVars{a, b}.~ \lA \neq \lB
  \end{array}
\end{displaymath}

And, as we see in the term $\lA = \lB$, the implication...

Now $\forall\lVars{foo}\;\lFoo=0$
\end{document}

在此輸入影像描述

相關內容