I'm studying macros and, as an exercise, I wanted to compute the successor of a number, represented as text, in binary, little endian (lsb first). After big effort I devised this:
\def\finish#1\relax{#1}
\def\go#1{\toks0={}%
\ifx#1\relax\toks0={1}\fi%
\if0#1\toks0={1\finish}\fi%
\if1#1\toks0={0\go}\fi%
\the\toks0}
The idea is to scan the number from the left and apply the obvious transformations, recurring when needed and copying the rest of the number otherwise.
I use \relax
as a marker for the end of the string: I was using \end
, taking inspiration from the TeXbook, but it didn't work here.
It works correctly in the first cases: \go\relax
and \go0\relax
produce 1
as the successor of 0
, \go1\relax
produces 01
.
Anyway, I can't understand why \go01\relax
yields an empty output.
Manually following the expansion and even substituting its fragments in place give the correct 11
.
What am I missing?
unravel
package rather useful.