Templates Considered Harmful
The program is a C++ type. The compiler runs it while working out what that type is.
feresum · Turing complete: unknown · ●●● hard
Tested with 8 known programs · Hello World on Try It Online: identical · Test method
Run it
The idea
C++ templates can compute, since the compiler has to work out every type, and a type can depend on numbers and other types. feresum turned that into a small functional language. A program is one template type, wrapped in Fun<...> and applied to the input. The answer is never run; g++ evaluates it while compiling, and the compiled program only prints the string it found.
The machine
| Type | Means |
|---|---|
Int<n>, I<n>, T, F | A 64-bit number; T is 1, F is 0 |
St<'a',98> | A string of characters |
Lst<...> | A list |
Fun<body> | A function |
A<n> | Argument n; A<0> is the function itself |
Ap<f, x, y> | Apply f |
Add Sub Mul Div Rem and bit operations, lt | Arithmetic and less than |
If<c, a, else> | Lazy choice; 0 and the empty string are false |
Str, Cat | Number to decimal, join two strings |
Hd Tl mt | Head, tail, is empty |
Recursion needs no fixed point combinator, since every function can see itself as A<0>. The runner allows only letters, digits, _, spaces, < > , and ', so there are no negative literals; Neg makes them. Anything that does not compile prints nothing.
Example
The second program is 10 factorial.
The second program is 10 factorial. The third repeats the input three times; the outer A<1> is the input, the inner ones are the inner function's own arguments.
Patterns it teaches
- Lambda encoding: functions, arguments and self-application are all there is to loop with.
- Hostile design: the compiler is the interpreter, and a mistake is a page of template errors.
Try this
- Print the sum of 1 to 100.
- Print 2 to the power 40 with lsl.
- Hard: print the first ten Fibonacci numbers, separated by spaces.
Further
- The reference, templates.h and runtmp.py
See also
Also in Functional and concatenative
Write your own in Run Convert a program from Templates Considered Harmful
Implementation
JavaScript interpreter, source and command line
A JavaScript interpreter, used in the browser and on the command line. Id: templates.
Command line
shib run templates -e 'A<1>' --input 'echo'shib manual templatesSource
- Module
langs/tio/ports.js- Interpreter
langs/tio/templates.js
Docs: Kernel instructions · The .shib format · Command line · Adding a language