I build two token lists, the first containing
{1^{2^{3^{4^{5^{6^{7
and the other containing
}}}}}}}
Actually, the braces are stored as \c_group_begin_token
and \c_group_end_token
, so the token lists are balanced.
If [
follows, a further step is taken. At the end, the two lists are delivered.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\tower}{}
{
\tl_clear:N \l__perner_tower_left_tl
\tl_clear:N \l__perner_tower_right_tl
\perner_tower_build:n { }
}
\tl_new:N \l__perner_tower_left_tl
\tl_new:N \l__perner_tower_right_tl
\cs_new_protected:Nn \perner_tower_build:n
{
\peek_charcode:NTF [
{% there is a [
\__perner_tower_add:nw { #1 }
}
{% no [, end
\__perner_tower_end:
}
}
\cs_new_protected:Npn \__perner_tower_add:nw #1 [#2]
{
\tl_put_right:Nn \l__perner_tower_left_tl { #1 \c_group_begin_token #2 }
\tl_put_right:Nn \l__perner_tower_right_tl { \c_group_end_token }
\perner_tower_build:n { \c_math_superscript_token }
}
\cs_new_protected:Npn \__perner_tower_end:
{
\tl_use:N \l__perner_tower_left_tl
\tl_use:N \l__perner_tower_right_tl
}
\ExplSyntaxOff
\begin{document}
$\tower[1][2][3][4][5][6][7]$
\end{document}
Much shorter with a different syntax. The argument is split at commas; then between any two items we output ^{
(again as implicit tokens) and at the end the right number of }
is output.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\tower}{m}
{
\perner_tower_build:n { #1 }
}
\seq_new:N \l__perner_tower_seq
\cs_new_protected:Nn \perner_tower_build:n
{
\seq_set_split:Nnn \l__perner_tower_seq { , } { #1 }
\seq_use:Nn \l__perner_tower_seq { \c_math_superscript_token \c_group_begin_token }
\prg_replicate:nn { \seq_count:N \l__perner_tower_seq - 1 } { \c_group_end_token }
}
\ExplSyntaxOff
\begin{document}
$\tower{1,2,3,4,5,6,7}$
\end{document}
\tower[2][3][4][2]
? Would\tower{2,3,4,2}
be an acceptable input format?