While being a typesetting system TeX also has powerful macro abilities that make it a Turing-complete programming language.

TeX commands commonly start with a backslash and are grouped with curly braces. Almost all of TeX’s syntactic properties can be changed on the fly which makes TeX input hard to parse by anything but TeX itself. Many commands, including most user-defined ones, are expanded on the fly until only unexpandable tokens remain which get executed. Expansion itself is practically side-effect free. Tail recursion of macros takes no memory, and if-then-else constructs are available.

TeX is a typesetting system designed and mostly written by Donald Knuth.

Examples:

Hello, World!:

Hello, World! \bye

Quadratic equation:

This example uses TeX fixed point arithmetic package fp and it’s macro for solving quadratic equations called \FPqsolve . Note that this macro can find only real roots of equation, and prints “FP error: Quadratic equation does not have a solution” if roots are complex (i.e., non-existent from its point of view).

\input fp.tex \message { A = } \read -1 to \a \message { B = } \read -1 to \b \message { C = } \read -1 to \c \FPqsolve { \xone }{ \xtwo }{

umber\a }{

umber\b }{

umber\c } $ \a x^ 2 + \b x + \c = 0 $ $ x_ 1 = \xone $ $ x_ 2 = \xtwo $ \bye



Quadratic equation: document generated by TeX example program

Factorial:

This example uses iterative factorial definition.

Note that \factorial macro has to use double curly brackets because it has loop that is used inside other loop.

Also only factorials up to 12 are handled. For bigger numbers TeX throws “Arithmetic overflow” error.



ewcount



ewcount\p

ewcount\m \def\factorial #1 {{ \m =#1 \advance\m by 1

=1 \p =1 \loop\ifnum

< \m \multiply\p by

\advance

by 1 \repeat

umber\p }} \def\printfactorials #1 { \m =#1 \advance\m by 1

=0 \loop\ifnum

< \m \hfil\break

umber

! = \factorial {

} \advance

by 1 \repeat } \printfactorials { 12 } \bye

Fibonacci numbers:

This example uses iterative process to calculate Fibonacci numbers.

Note that \fibonacci macro has to use double curly brackets because it has loop that is used inside other loop.