1

Consider the following example:

\documentclass{article}

\usepackage{xparse}

% http://tex.stackexchange.com/a/246924/15874
\ExplSyntaxOn
  \NewDocumentCommand{\countlist}{m}{\clist_count:n{#1}}
\ExplSyntaxOff

\newcommand*\liste{
  \marsvin,
  \hund,
  \kat,
  \hoens,
  \hest,
  \fisk,
  \fugl,
  \kanin,
  \oerkenrotte,
  \slange,
  \gris,
  \hamster
}
\newcommand*\str{\countlist{\liste}}

\begin{document}

% data
\def\marsvin{1}
\def\hund{12}
\def\kat{14}
\def\hoens{2}
\def\hest{5}
\def\fisk{3}
\def\fugl{2}
\def\kanin{2}
\def\oerkenrotte{1}
\def\slange{1}
\def\gris{1}
\def\hamster{1}

Number of elements: \str

\end{document}

In this example \str prints the number 1 but I would like it to print 12.

I guess the problem is that function counts the number of lists and not the number of elements in the list.

How do I solve this problem?

P.S. If I use

\newcommand*\str{\countlist{
  \marsvin,
  \hund,
  \kat,
  \hoens,
  \hest,
  \fisk,
  \fugl,
  \kanin,
  \oerkenrotte,
  \slange,
  \gris,
  \hamster
}}

everything is fine.

1 Answers1

2

You're asking to count the items in the comma separated list you're passing as argument: in the case \countlist{\liste} there is only one item.

If the lists you're counting the elements of are always contained in a macro, you want

\NewDocumentCommand{\countlist}{m}
 {
  \clist_count:N #1
 }

With this change, your code gives

enter image description here

However, I'd prefer defining \countlist with a *-variant for “implicit lists”.

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\countlist}{sm}
 {
  \IfBooleanTF{#1}
   {
    \clist_count:o { #2 }
   }
   {
    \clist_count:n { #2 }
   }
 }
\cs_generate_variant:Nn \clist_count:n { o }
\ExplSyntaxOff

\newcommand*\liste{
  \marsvin,
  \hund,
  \kat,
  \hoens,
  \hest,
  \fisk,
  \fugl,
  \kanin,
  \oerkenrotte,
  \slange,
  \gris,
  \hamster
}

\begin{document}

% data
\def\marsvin{1}
\def\hund{12}
\def\kat{14}
\def\hoens{2}
\def\hest{5}
\def\fisk{3}
\def\fugl{2}
\def\kanin{2}
\def\oerkenrotte{1}
\def\slange{1}
\def\gris{1}
\def\hamster{1}

Number of elements: \countlist*{\liste}

Number of elements: \countlist{
  \marsvin,
  \hund,
  \kat,
  \hoens,
  \hest,
  \fisk,
  \fugl,
  \kanin,
  \oerkenrotte,
  \slange,
  \gris,
  \hamster
}

\end{document}

enter image description here

Here I use the o variant, because \liste is not really a clist variable; but it's being picky.

egreg
  • 1,121,712