Handling loops in expl3

The command \clist_put_right:Nn will leave \l_tmpa_tl in the input, i.e. at the time of calling \result to check for the equality, \l_tmpa_tl contains 5 and \l_tmpb_tl contains e.

However, to get the pairwise content X/Y, the current value of \l_tmpa_tl and \l_tmpb_tl must be evaluated (expanded) and stored to the \clist variable, so use the x type:

\clist_put_right:Nx #3 {\l_tmpa_tl/\l_tmpb_tl}

Most likely a \seq list could be faster, but this depends on the use case.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\pairwise}{mmm}{
  \clist_set_eq:NN \l_tmpa_clist #1
  \clist_set_eq:NN \l_tmpb_clist #2
  \clist_clear:N #3
  \bool_until_do:nn {\clist_if_empty_p:N \l_tmpa_clist}{
    \clist_pop:NN \l_tmpa_clist \l_tmpa_tl
    \clist_pop:NN \l_tmpb_clist \l_tmpb_tl
    \clist_put_right:Nx #3 {\l_tmpa_tl / \l_tmpb_tl}
  }
}
\ExplSyntaxOff

\begin{document}

\def\this{1,2,3,4,5}
\def\that{a,b,c,d,e}

There is \{\this\} and \{\that\}.

\pairwise{\this}{\that}{\result}
\def\expected{1/a,2/b,3/c,4/d,5/e}

Now \{\result\} is equal to \{\expected\}?

\end{document}

enter image description here


You have to use the value of the token list variable, not the token list.

Here's a different approach using sequences and \seq_mapthread_function:NNN, that traverses two sequences and hands the items to a two argument function.

You can give a different output separator as optional argument to `\pairwise, so for example

\pairwise[|]{a,b}{1,2}{\result}

would define \result to a/1|b/2.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\pairwise}{O{,}mmm}
 {
  \seq_set_from_clist:No \l_komarov_first_seq { #2 }
  \seq_set_from_clist:No \l_komarov_second_seq { #3 }
  \seq_clear:N \l_komarov_output_seq
  \seq_mapthread_function:NNN
    \l_komarov_first_seq
    \l_komarov_second_seq
    \komarov_addentry:nn
  \tl_set:Nx #4 { \seq_use:Nn \l_komarov_output_seq { #1 } }
 }
\seq_new:N \l_komarov_first_seq
\seq_new:N \l_komarov_second_seq
\seq_new:N \l_komarov_output_seq
\cs_generate_variant:Nn \seq_set_from_clist:Nn { No }
\cs_new_protected:Nn \komarov_addentry:nn
 {
  \seq_put_right:Nn \l_komarov_output_seq { #1 / #2 }
 }
\ExplSyntaxOff

\begin{document}

\newcommand\this{1,2,3,4,5}
\newcommand\that{a,b,c,d,e}

There is \{\this\} and \{\that\}.

\pairwise{\this}{\that}{\result}
\newcommand\expected{1/a,2/b,3/c,4/d,5/e}

Now \{\result\} equals \{\expected\}

\pairwise{1,2,3,4,5}{a,b,c,d,e}{\newresult}

Also \{\newresult\} equals \{\expected\}

\end{document}

enter image description here

Tags:

Loops

Expl3