[Tex/LaTex] Understanding a \@for loop

latex-baseloopsmacros

I'm having trouble with a \@for loop. I've got a macro that takes a comma delimited list and puts each element into a row of an array. When I do this using a \@for loop, I get an extra row that I don't understand. I can manually get rid of it with a negative space, (as in the commented line below) but that can't be the right way to do it, so I must be doing something wrong. Here's a minimal example. For comparison, if I construct what I expect the result of the loop to be manually, the extra row doesn't appear.

\documentclass{article}
\usepackage{amsmath}
\makeatletter
\newcommand{\fbun}[1]
   {\ensuremath{\left[\begin{array}{c}
      \@for\xx:=#1\do {\text{\xx}\\}
%     \\ [-2.75ex] % why is this required?
      \end{array}\right]}}
\makeatother
\begin{document}
$\left[\begin{array}{c}
      A\\
      B\\
      C\\
      D\\
      \end{array}\right]$
% same array, but generated by a macro
\fbun{A,B,C,D}
\end{document}

output of code

Best Answer

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}
Related Question