foreach-loop in align

Here I build a token list, and then pass it to align*. The use of \xaddtotoks allows the first token in the list (here \x) to be expanded once in the building of the token list.

\documentclass{article}
\usepackage{listofitems,amsmath}
\newtoks\alignbuild
\newcommand{\addtotoks}[2]{#1\expandafter{\the#1#2}}
\newcommand{\xaddtotoks}[2]{\expandafter\addtotoks\expandafter#1\expandafter{#2}}
\begin{document}
\readlist\mylist{1,2,3,666}
\foreachitem\x\in\mylist{%
  \xaddtotoks\alignbuild{\x : }%
  \xaddtotoks\alignbuild{\x &= }%
  \xaddtotoks\alignbuild{\x\\}%
}
\def\tmp{\begin{align*}}
\expandafter\tmp\the\alignbuild
\end{align*}
\end{document}

enter image description here


Here's a fairly general macro that takes four mandatory arguments and one optional as described in the code.

The idea is to define a scheme for the input, in the examples it is #1/#2, but it can be whatever with any number of arguments (up to nine, of course); we also define the template for each row, using #1 and so on for the actual arguments to be substituted; finally, the input. The optional argument is for accommodating alignat or alignedat that need to know the number of column pairs to be typeset.

An internal function is defined to deliver the required template; then it is a matter of splitting the input at commas and feed each item to the template function.

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

\ExplSyntaxOn

\NewDocumentCommand{\makealignment}{mommm}
 { % #1 = environment
   % #2 = optional for alignat
   % #3 = scheme for the variables
   % #4 = scheme for the rows
   % #5 = items
   \cs_set_protected:Npn \__hennich_row:w #3 \q_stop { #4 }
   \seq_set_split:Nnn \l__hennich_input_seq { , } { #5 }
   \seq_set_map:NNn
     \l__hennich_output_seq
     \l__hennich_input_seq
     { \__hennich_row:n { ##1 } }
   \IfNoValueTF{#2}{\begin{#1}}{\begin{#1}{#2}}
   \seq_use:Nn \l__hennich_output_seq { \\ }
   \end{#1}
 }

\seq_new:N \l__hennich_input_seq
\seq_new:N \l__hennich_output_seq
\cs_new_protected:Nn \__hennich_row:n { \__hennich_row:w #1 \q_stop }

\ExplSyntaxOff

\begin{document}

\makealignment{align*}
  {#1/#2}
  {#1_{i} : #1 &= #1 & i&=#2}
  {a/3, b/5, foo/0}

\makealignment{alignat}[2]
  {#1/#2}
  {#1_{i} : #1 &= #1 &\qquad i&=#2}
  {a/3, b/5, foo/0}

\end{document}

enter image description here

Tags:

Foreach