I'm looking for simple examples of using TeX as a programming language, not LaTeX, and ideally these examples only use the primitive TeX commands. Why? Because the members of a local computer club take turns talking about offbeat languages, and it will be my turn soon. The audience ranges from programming neophytes to people with a sophisticated understanding of computer science. I'm trying to come up with examples that everyone can understand, and that also demonstrate how TeX "works."

I'm aware of a few examples along these lines, not all of which are as primitive as I would like:

Count the number of elements of each size in a list

Position of largest element in a list

Count number of elements in a list

Find the number of elements in a list that occurs most often

Macros with binary trees as arguments

How to produce a list of prime numbers in LaTeX

How to make the last word in a sequence the first

\rand inside \forloop creates identical values

Stack datastructure using LaTeX

Delete and element from a comma delimited list

As long as we're making a list, it's worth including things on the fun/crazy end of the spectrum too. I'm aware of:

a brainf**k intepreter

BaSiX -- An Interpreter Written in TeX

Lists in TeX's Mouth (lambda calculus in TeX)

An AVR Emulator written in pure LaTeX

Finally, are there certain design patterns or paradigms that are particular to TeX (or macro-based languages in general)? Other languages have things like lambdas, or they may be strongly, weakly, dynamically or statically typed. Some languages lean on encapsulation or being object-oriented, and there's a whole universe of design patterns that fall under the umbrella of "object-oriented." TeX seems to be off in its own world.

  • 2
    The ability of TeX to modify its own syntax should be mentioned, with the famous example ctan.org/pkg/xii and also ctan.org/pkg/inscrutable.
    – Marijn
    Feb 14, 2022 at 14:52
  • I think the two aspects I'd emphasise are macros (i.e. that \foo is replaced by it's definition at point-of-use), and expansion (i.e. that some things work by expansion, others by execution, and we sometimes need to keep everything in the input stack to work expandably).
    – Joseph Wright
    Feb 14, 2022 at 15:00
  • I wonder if the question is really answerable: it feels very opinion-based
    – Joseph Wright
    Feb 14, 2022 at 15:01
  • It's my answer, but I think tex.stackexchange.com/a/69771 (trimming spaces by expansion) nicely shows off how TeX works in expansion, in a task that people do need in a variety of languages
    – Joseph Wright
    Feb 14, 2022 at 15:13
  • Maybe some answers in this link if you haven't already seen them. tex.stackexchange.com/q/104248/70641
    – James
    Feb 14, 2022 at 16:00


You must log in to answer this question.

Browse other questions tagged .