# Recursively defined macros in TeX

After receiving a nice answer to a previous question, I got enthousiastic and tried to create a macro \sum such that \sum<1+2+3> would be expanded into 6.

My idea was to work recursively, using the parsing functionality of \def. For instance, the following code outputs "7+6+5"

\documentclass{article}
\def\sumtestX<#1+#2>{\ifx\empty#2{#1}\else{\sumtestX<#2>+#1 }\fi}
\def\sumtest<#1>{\sumtestX<#1+\empty>}

\begin{document}
\sumtest<5+6+7>
\end{document}


So one would expect that turning the "+" into a real "sum" would calculate the actual sum. Nevertheless, the following code doe not work.

\documentclass{article}
\def\sum#1+#2{\the\numexpr#1+#2\relax}
\def\sumtestX<#1+#2>{\ifx\empty#2{#1}\else{\sum\sumtestX<#2>+#1 }\fi}
\def\sumtest<#1>{\sumtestX<#1+\empty>}

\begin{document}
\sumtest<5+6+7>
\end{document}


"Missing number, treated as zero" !? What's wrong?

-

Actually some curly braces were wrong and some curly braces are missing around arguments. For analyzing/debugging the setting \tracingmacros=1 is helpful.

\documentclass{article}
\def\sum#1+#2{%
\the\numexpr#1+#2\relax
}
\def\sumtestX<#1+#2>{%
\ifx\empty#2%
#1%
\else
\sum{\sumtestX<#2>}+{#1}% argument braces
\fi
}
\def\sumtest<#1>{\sumtestX<#1+\empty>}

\begin{document}
\sumtest<5+6+7>
\end{document}


Of course, the recursive definitions are only an exercise? \sumtest could be defined much easier:

\def\sumtest<#1>{\the\numexpr(#1)\relax}

-
Thank you! (Actually I was seriously going to use this >_> ... as part of my 'solution' for the problem that occurs when trying to calculate sums of "empty" strings, e.g. 5++5=10 or 4+3+=7. But I just found out that appending a +0 always solves that problem.) –  Archibald Nov 17 '12 at 22:35
@Archibald You want more exercises? Strings starting with + as in +1+2, supporting - as binary (and unary) operator, parentheses, ... –  Heiko Oberdiek Nov 17 '12 at 22:38

LuaTeX is an ideal choice for such macros. For example, in ConTeXt, you can define:

\def\simplemath<#1>{\ctxlua{context(#1)}}
\starttext
\simplemath<1+2+3> \simplemath<2*4+5>
\stoptext


and in (Lua)LaTeX you can define:

\documentclass{minimal}

\def\simplemath<#1>{\directlua{tex.print(#1)}}

\begin{document}
\simplemath<1+2+3> \simplemath<2*4+5>
\end{document}


Note that this works for all types of mathematical expressions, and not just addition.

-