Although there is already a ↗question with a similar title, I take the risk of asking again, because the linked topic is a bit bloated in my opinion, the answers/solutions too complicated.
So here is a more generic example:
\def\recursion#1\nil{%
\ifnum#1>0
\expandafter\recursion\the\numexpr #1-1\relax\nil%
{#1}%
\else%
{Start}{0}%
\fi%
}
\edef\result{\recursion 4997\nil} %works up to 4996
\show\result %`{Start}{0}{1}{2}{3}...'
\bye
It saves the result {Start}{0}{1}{2}{3}...{<initial value>} in \result. Thus, the wanted recursion macro is expected to be expandable.
With default settings of TeX Live, the code above only works for initial values up to 4996, but else fails with ! TeX capacity exceeded, sorry [input stack size=5000]., probably due to nesting of \ifnum... clauses.
In an attempt to solve the problem, I tried to put off the recursion call behind the \fi as follows:
\def\recursion#1\nil{%
\ifnum#1>0
\expandafter\firstoftwo%
\else%
\expandafter\secondoftwo%
\fi%
{%
\expandafter\recursion\the\numexpr #1-1\relax\nil%
{#1}%
}{%
{Start}{0}%
}%
}
\def\firstoftwo#1#2{#1}
\def\secondoftwo#1#2{#2}
\edef\result{\recursion 2499\nil}
\show\result %`{Start}{0}{1}{2}{3}...'
\bye
To my great surprise this code fails even earlier, namely for initial values greater than 2498.
So, what is going wrong here? How can I solve the problem of stack overflow?