TPK algorithm
The TPK algorithm is a simple program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages. In their 1977 work "The Early Development of Programming Languages", Trabb Pardo and Knuth introduced a small program that involved arrays, indexing, mathematical functions, subroutines, I/O, conditionals and iteration. They then wrote implementations of the algorithm in several early programming languages to show how such concepts were expressed.
To explain the name "TPK", the authors referred to Grimm's law, the sounds in the word "typical", and their own initials. In a talk based on the paper, Knuth said:
The algorithm
Knuth describes it as follows:In pseudocode:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
call a function to do an operation
if result overflows
alert user
else
print result
The algorithm reads eleven numbers from an input device, stores them in an array, and then processes them in reverse order, applying a user-defined function to each value and reporting either the value of the function or a message to the effect that the value has exceeded some threshold.
Implementations
Implementations in the original paper
In the original paper, which covered "roughly the first decade" of the development of high-level programming languages, they gave the following example implementation "in a dialect of ALGOL 60", noting that ALGOL 60 was a later development than the languages actually discussed in the paper:TPK: begin integer i; real y; real array a;
real procedure f; real t; value t;
f := sqrt + 5 × t ↑ 3;
for i := 0 step 1 until 10 do read;
for i := 10 step -1 until 0 do
begin y := f;
if y > 400 then write
else write;
end
end TPK.
As many of the early high-level languages could not handle the TPK algorithm exactly, they allow the following modifications:
- If the language supports only integer variables, then assume that all inputs and outputs are integer-valued, and that
sqrtmeans the largest integer not exceeding. - If the language does not support alphabetic output, then instead of the string
'TOO LARGE', output the number 999. - If the language does not allow any input and output, then assume that the 11 input values have been supplied by an external process somehow, and the task is to compute the 22 output values .
- If the language does not allow programmers to define their own functions, then replace
fwith an expression equivalent to.
Implementations in more recent languages
C">C (programming language)">C implementation
This shows a C implementation equivalent to the above ALGOL 60.- include
- include
int main
Python">Python (programming language)">Python implementation
This shows a Python implementation.from math import sqrt
def f:
return sqrt + 5 * t**3
a =
for i, t in reversed:
y = f
Rust">Rust (programming language)">Rust implementation
This shows a Rust implementation.use std::;
fn f -> Option
fn main