0

I want to check the sum of a sequence of variables. I created a function which returns this sum. But when I use it I get an error.

\documentclass{article}
\usepackage{expl3}
\pagestyle{empty}
\ExplSyntaxOn
\int_set:Nn \l_tmpa_int{1}
\int_set:Nn \l_tmpa_int{2}
\seq_const_from_clist:Nn \g__variables_seq{\l_tmpa_int,\l_tmpb_int}
\cs_new_protected:Nn \g__sum:{
\int_zero_new:N \l__sum_seq_int
\seq_map_inline:Nn \g__variables_seq {
\int_set:Nn \l__sum_seq_int{\int_eval:n{\l__sum_seq_int+##1}}
}
\int_use:N \l__sum_seq_int
}
\int_case:nnF{\g__sum:}{{1}{\message{one}}}{\message{many}}
\ExplSyntaxOff
\begin{document}

\end{document}
1
  • You cannot use non-expandable material in an integer expression
    – Joseph Wright
    Dec 3, 2020 at 7:23

1 Answer 1

2

I guess you have some sequence populated with integers, either explicit or implicit (that is, stored in integer variables) and you want to return the sum.

\documentclass{article}

%\usepackage{expl3} % not needed with recent LaTeX kernel

\ExplSyntaxOn

\cs_new:Nn \ak_foo_sequence_sum:N
 {% the argument is a sequence variable
  \int_eval:n { \seq_use:Nn #1 { + } }
 }

\begin{document}

% test

\int_set:Nn \l_tmpa_int { 2 }
\int_set:Nn \l_tmpb_int { -4 }

\seq_set_from_clist:Nn \l_tmpa_seq { \l_tmpa_int, 23, \l_tmpb_int , 21 }

%%% just print the sum
\ak_foo_sequence_sum:N \l_tmpa_seq

\par

%%% now use the function to set an integer variable
\int_set:Nn \l_tmpa_int { \ak_foo_sequence_sum:N \l_tmpa_seq }
%%% print the result
\int_to_arabic:n { \l_tmpa_int }

\end{document}

You get in both case 42.

The function \seq_use:Nn delivers “all at once” (in a full expansion context) the items in the sequence specified as first argument all separated by the tokens specified in the second argument. In an integer expression, +- is legal.

Thus you can use \ak_foo_sequence_sum:N <sequence> everywhere an integer expression is expected, including the first argument of \int_case:nnF.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .