Understanding a \@for loop
As Altermundus said, you cannot add extra {}
or \relax
or other invisible material after the last row of the tabular
. However, there is some extra material added after \@for
. The implementation of \@for
is not very good for this.
Since the \@for
in LaTeX2e kernel has restrictions, I suggest \forcsvlist
from etoolbox
:
\documentclass{article}
\usepackage{amsmath}
\usepackage{etoolbox}
\def\addrow#1{\text{#1}\\}
\newcommand{\fbun}[1]
{\ensuremath{\left[\begin{array}{c}
\forcsvlist\addrow{#1}%
\end{array}\right]}}
\begin{document}
$\left[\begin{array}{c}
A\\
B\\
C\\
D\\
\end{array}\right]$
\fbun{A,B,C,D}
\end{document}
In "User's Guide and Reference Manual" Leslie Lamport writes page 45:
There must be no
&
after the last item in a row and no\\
after the last row.
$\left[\begin{array}{c}
A\\
B\\
C\\
D\\{}%
\end{array}\right]$
This code gives a new line with an empty group. Each cell of an array is in a group.
\@for
is a no developable loop
so you need to write something like
\fbun{A,B,C}
D
or you can create a developable loop
but it's more complicated :
\makeatletter
\newcommand*{\For}[1]{\noalign{\gdef\@Do##1{#1}}\@For}
\newcommand*{\@For}[3]{%
\unless\ifnum#1 \ifnum#3>0 >\else <\fi #2
\@Do{#1}%
\expandafter\@For\expandafter{\number\numexpr#1+#3}{#2}{#3}%
\fi
}
\makeatother
$\left[\begin{array}{c}
\For{\@Alph{#1}\\}{1}{4}{1}
\end{array}\right]$
\For
is a developable loop
for example, you can try :
\begin{tabular}{ll}
\For{A number & #1\\}{1}{20}{1}
\end{tabular}
The problem is that TeX finds something following the last \\
which starts a new row (it's neither \noalign
nor \crcr
that wouldn't).
A solution might be to use a token register: we develop the loop while in the first cell, so there's no problem of \xx
not being defined any more after TeX has seen \\
(or &
).
\usepackage{amsmath}
\makeatletter
\newcommand{\fbun}[1]{%
\begin{bmatrix}
\toks@={\@gobble}%
\@for\next:=#1\do
{\toks@=\@xp{\the\@xp\toks@\@xp\\\@xp\text\@xp{\next}}}%
\the\toks@
\end{bmatrix}}
\makeatother
I've used \@xp
(from amsmath) that's a shorthand for \expandafter
; if the \text
around the entry wasn't required, then
\toks@=\expandafter{\the\expandafter\toks@\next}
would have sufficed. Initializing \toks@
to \@gobble
has the effect that the first \\
is swallowed.
Instead of array
I've used bmatrix
(change it if you like) and, of course, I deleted \ensuremath
as the first step. :)