I've assigned an array and I want to design a command (Assume it's named \arraynum
) with 2 values to print the number of elements in the first and second rows of an array respectively, for example
\documentclass{article}
\usepackage{tikz}
\makeatletter
\ExplSyntaxOn
\cs_set:Npn \MyArray #1 {
\gdef\@MyArray{#1}
\gdef\@Arraynum{\clist_count:n {#1}}
\seq_set_split:Nnn \l_node_row_seq {;} {#1}
\int_step_inline:nn{\seq_count:N \l_node_row_seq}
{
\seq_if_exist:cF {l_node_row_##1_seq}
{
\seq_new:c {l_node_row_##1_seq}
}
\exp_args:Ncx\seq_set_from_clist:Nn {l_node_row_##1_seq} {\seq_item:Nn \l_node_row_seq{##1}}
}
}
\ExplSyntaxOff
\begin{document}
\MyArray{
1,2,3,4,5,6,7;
$\alpha$,$\beta$,$\gamma$,$\delta$,$\epsilon$
}
There are \@Arraynum{} elements in the array, 7 elements in the first line while 5 elements in the second line.
\end{document}
There are 7 elements in the first line, so the command \arraynum[1]{}
the command \arraynum[1]{@MyArray}
should print 7 while the command \arraynum[2]{@MyArray}
should print 5. So, how can I design this command?
Whats's more, as you can see, there are 12 elements in the array in total, while the first line and the second line were separated by the symbol ;
, but the command \clist_count:n {\@MyArray}
couldn't recognize the separate symbol ;
so it print 11
while the correct number is 12
. How can I solve these problems?
Best Answer
You can make better use of
expl3
so you can define as many arrays as you want and retrieve information from them in a uniform way.As a general rule, don't mix
\gdef
withexpl3
.Note that the “step 2” commands below are fully expandable.
Step 1. Set up an infrastructure for arrays.
Step 2. Define commands to work with these arrays, for instance “count items” or “retrieve one item”.
Here's the code: the array is saved as a sequence of clists.
You see that
\arraycount
computes the full length; if you pass an optional argument you get the length of the corresponding row; instead,\arraycount*{<name>}
computes the number of lines.You can test full expandability by doing
You can do, in the same document,
and you'll get