[Tex/LaTex] Use recursion in LaTeX3

expl3

I want to use recursion to calculate n! in LaTeX3, but found that the result is not correct, mwe is as follows

\documentclass{article}                          
\ExplSyntaxOn
\cs_set:Nn \froac:n {
\int_compare:nNnTF{#1}={0}{1}
{
     \int_eval:n{#1*\froac:n{#1-1}}
}
}
\ExplSyntaxOff
\begin{document}
\ExplSyntaxOn
\froac:n{4}
\ExplSyntaxOff
\end{document}

thank you!

Best Answer

Remember that TeX is a macro language. Let's manually expand two steps of your recursion to see what's going on:

You started with

\froac:n{4}

Since 4 is not 0, this becomes

\int_eval:n{4*\froac:n{4-1}}

Now 4-1 is still not 0, so the next iteration step results in

\int_eval:n{4*\int_eval:n{4-1*\froac:n{4-1-1}}}

Of course 4-1*\froac:n{4-1-1} is not actually what you want. You can fix this by adding parentheses:

\documentclass{article}                          
\ExplSyntaxOn
\cs_set:Nn \froac:n {
\int_compare:nNnTF{#1}={0}{1}
{
     \int_eval:n{(#1)*\froac:n{(#1)-1}}
}
}
\ExplSyntaxOff
\begin{document}
\ExplSyntaxOn
\froac:n{4}
\ExplSyntaxOff
\end{document}

Related Question