8

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?

0

2 Answers 2

9

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} 
2
  • 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.) Commented Nov 17, 2012 at 22:35
  • @Archibald You want more exercises? Strings starting with + as in +1+2, supporting - as binary (and unary) operator, parentheses, ... Commented Nov 17, 2012 at 22:38
5

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.