将对齐制表符传递给 \ifx

将对齐制表符传递给 \ifx

我有以下宏

\usepackage{xintexpr}

\newcommand\seq[4] %length, delimiter, generating func, last term
{%
  \def\s##1{\def\n{##1} #3}
  \xintListWithSep{#2}
  {%
    \xintApply{\s}{\xintSeq{1}{#1}}
  }%
  #2\ldots
  \ifx\\#4\\ %if 4th arg empty
    %empty
  \else
    #2#4
  \fi
}

该类型设置具有给定生成函数的序列,即

$\seq{3}{,}{\n}{n}$
$\seq{4}{,}{\n}{}$
$\seq{3}{,}{\sqrt{\n}}{}$
$\seq{3}{/}{\frac{1}{\n}}{\frac{1}{n}}$

相当于

$1, 2, 3, ..., n$
$1, 2, 3, 4, ...$
$\sqrt{1}, \sqrt{2}, \sqrt{3}, ...$
$\frac{1}{1}/ \frac{1}{2}/ \frac{1}{3}/ .../ \frac{1}{n}$

尽管它可以按预期工作,但是当它处于支持对齐的环境中并传递对齐制表符(&)作为第二个参数并且第四个参数为空时,它会失败,即

\begin{align}
  \seq{3}{&&,}{\n}{n} % this works
  \seq{3}{&&,}{\n}{}  % this causes an error 
\end{align}

在修改了代码之后,我得出结论,错误是由语句\ifx仅在评估字符%empty并以字符开头时引起的,如下例所示:

\documentclass{article}

\usepackage{amsmath}

\newcommand\testa[2]
{%
  \ifx\\#2\\
    %empty, evaluation causes error
  \else
    #1
  \fi
}

\newcommand\testb[2]
{%
  \ifx\\#2\\
    #1
  \else
    %full, evaluation causes error
  \fi
}

\begin{document}
\begin{align}
  \testa{&}{n}    \\ %ok
  \testb{&}{}     \\ %ok
%
  \testa{&}{}     \\ %ok
  \testb{&}{n}    \\ %ok
%
  foo\testa{&}{n} \\ %ok
  foo\testb{&}{}  \\ %ok
%
  foo\testa{&}{}  \\ % causes error
  foo\testb{&}{n}    % causes error
\end{align}
\end{document}

如何改变条件来处理对齐制表符?

如果问题太具体,请告诉我,我会删除它。

编辑:添加\usepackage{amsmath}到示例中

答案1

您需要隐藏&被跳过的分支

\documentclass{article}
\usepackage{amsmath}

\def\useone#1{#1}
\newcommand\testa[2]
{%
  \ifx\\#2\\%%
    %empty, evaluation causes error
  \else
    \useone{#1}%%
  \fi
}

\newcommand\testb[2]
{%
  \ifx\\#2\\%%
    \useone{#1}%%
  \else
    %full, evaluation causes error
  \fi
}

\begin{document}
\begin{align}
  \testa{&}{n}    \\ %ok
  \testb{&}{}     \\ %ok
%
  \testa{&}{}     \\ %ok
  \testb{&}{n}    \\ %ok
%
  foo\testa{&}{n} \\ %ok
  foo\testb{&}{}  \\ %ok
%
  foo\testa{&}{}  \\ % causes error
  foo\testb{&}{n}    % causes error
\end{align}
\end{document}

相关内容