[comp.text.tex] Karl Berry on loops and conditionals in TeX

bed_gdg@SHSU.BITNET (George D. Greenwade) (02/13/91)

This is another message I found in the genral delivery mailbox as I was
checking out what happened yesterday.  It was originally received on Mon, 11
Feb 1991 14:08:26 CST from William R(ay) Brohinsky
<RAYBRO%HOLON@utrcgw.utc.com>.
 
Also, if you requested a file from FILESERV yesterday and have not received it
by tomorrow, it probably got caught in this queue.  Sorry.  Please re-submit
your request and all should get there.
               -----------------------------------------------
From Karl Berry, some thoughts on loops and conditionals in TeX,
prompted my me in personal correspondance. I found Karl to be
very helpful, prompt, and approachable. His address in in
`TeX for the Impatient'.
 
-------------------8<-----cut here----------------------------------------
 
[H]ere are some random facts about conditionals and
loops that I've learned.  Feel free to pass it on anywhere you like.
 
When you make a new conditional in TeX, as in \newif\foo, it's not
particularly like defining a boolean variable `foo' in a programming
language.  There is no ``place'' where the result of the test is stored.
All that happens is a new control sequence \iffoo is defined, and
initially \let = to \iffalse.  When you say \footrue or \foofalse, no
new cs's are defined -- \iffoo is just \let to \iftrue or \iffalse,
respectively.  So, the code
\newif\iffoo
\iffoo a\else b\fi
 
is exactly equivalent to
\iffalse a\else b\fi
 
that is,
b
 
You can't invert conditions directly.  The only thing to do is leave out
the <true part>, as in
\iffoo\else a\fi
 
Unfortunately, this doesn't work in loops.  TeX has no primitives
concerning loops; the only thing it knows how to do is expand
tail-recursive macros.  The \loop macro in plain TeX exploits this, of
course.  It may be possible to define a different and better \loop that
allows inverted conditions and the like, but I haven't thought about it.
 
One painful truth about conditionals is that they don't expand the way
one would (usually) wish.  Suppose I have
 
\def\mac{...\futurelet\next\finishmac}
\iftrue \mac\else a\fi
 
\futurelet is going to set \next to the token `\else', a pretty much
useless thing to do. Usually, one
wants to be the thing after the \fi.  The solution is to use
\aftergroup:
 
\begingroup \iftrue\aftergroup\mac\else a\fi \endgroup
 
 
In general, TeX as a programming language leaves something to be
desired.  But one usually can get the job done...
 
 
---------------------8<----Cut Here-------------------------------
 
I can't say I'm too happy about that last statement, moreso for it being
true...
 
raybro