Trabb Pardo-Knuth algorithm
Encyclopedia
The Trabb Pardo–Knuth algorithm is a program
Computer program
A computer program is a sequence of instructions written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute...

 introduced by Donald Knuth
Donald Knuth
Donald Ervin Knuth is a computer scientist and Professor Emeritus at Stanford University.He is the author of the seminal multi-volume work The Art of Computer Programming. Knuth has been called the "father" of the analysis of algorithms...

 and Luis Trabb Pardo to illustrate the evolution of computer programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s.

In their 1977 work "The Early Development of Programming Languages", Trabb Pardo and Knuth introduced a trivial program which involved arrays, indexing
Index (information technology)
In computer science, an index can be:# an integer that identifies an array element# a data structure that enables sublinear-time lookup -Array element identifier:...

, mathematical function
Function (mathematics)
In mathematics, a function associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output. A function assigns exactly one output to each input. The argument and the value may be real numbers, but they can...

s, subroutine
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

s, I/O
I/O
I/O may refer to:* Input/output, a system of communication for information processing systems* Input-output model, an economic model of flow prediction between sectors...

, conditional
Conditional
Conditional may refer to:*Causal conditional, if X then Y, where X is a cause of Y*Conditional mood , a verb form in many languages*Conditional probability, the probability of an event A given that another event B has occurred...

s and iteration
Iteration
Iteration means the act of repeating a process usually with the aim of approaching a desired goal or target or result. Each repetition of the process is also called an "iteration," and the results of one iteration are used as the starting point for the next iteration.-Mathematics:Iteration in...

. They then wrote implementations of the algorithm in several early programming languages to show how such concepts were expressed.

The simpler Hello world program
Hello world program
A "Hello world" program is a computer program that outputs "Hello world" on a display device. Because it is typically one of the simplest programs possible in most programming languages, it is by tradition often used to illustrate to beginners the most basic syntax of a programming language, or to...

 has been used for much the same purpose.

The algorithm


ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
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.

ALGOL 60
ALGOL 60
ALGOL 60 is a member of the ALGOL family of computer programming languages. It gave rise to many other programming languages, including BCPL, B, Pascal, Simula, C, and many others. ALGOL 58 introduced code blocks and the begin and end pairs for delimiting them...


begin integer i; real y; real array a[0:10];
real procedure f(t); real t; value t;
f := sqrt(abs(t)) + 5*t^3;
for i := 0 step 1 until 10 do read(a[i]);
for i := 10 step -1 until 0 do
begin y := f(a[i]);
if y > 400 then write(i, "TOO LARGE")
else write(i,y);
end
end


The problem with the usually specified function is that the term 5*t^3 gives overflows in almost all languages for very large negative values.

Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...


import Control.Monad

main :: IO
main = mapM_ (maybe (putStrLn "TOO LARGE") print.f.read) . reverse =<< replicateM 11 getLine

f :: Double -> Maybe Double
f x = mfilter (<=400) $ Just $ sqrt (abs x) + 5*x^3

Haskell uses monads for input/output and the Maybe data type to signal overflow.

Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...


import math

def f(x):
return math.sqrt(abs(x)) + 5 * x**3

vals = [float(raw_input) for i in range(11)]
for i, x in enumerate(reversed(vals)):
y = f(x)
print('{0}: {1}'.format(i, y if y <= 400 else 'TOO LARGE'))


Floating point in Python on most platforms is IEEE-754, which can return "nan" and "inf" values, or raise an appropriate Python exception.

Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

The Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

 version takes advantage of some of its features:

def f(x)
Math.sqrt(x.abs) + 5*x ** 3
end

(0...11).collect{ gets.to_i }.reverse.each do |x|
y = f(x)
puts "#{x} #{y.infinite? ? 'TOO LARGE' : y}"
end

OCaml

The OCaml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...

 version using imperative features such as for loops:


let tpk =
let f x = sqrt x +. 5.0 *. (x ** 3.0) in
let pr f = print_endline (if f > 400.0 then "overflow" else string_of_float f) in
let a = Array.init 11 (fun _ -> read_float ) in
for i = 10 downto 0 do
pr (f a.(i))
done


A functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 version can also be written in OCaml:


let tpk l =
let f x = sqrt x +. 5.0 *. (x ** 3.0) in
let p x = x < 400.0 in
List.filter p (List.map f (List.rev l))

Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

A Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 version using exceptions might look like this:


sub f {
return sqrt(abs($_[0])) + 5*$_[0]**3;
}

for (1..11) {
push @inputs, <>;
}

for (reverse @inputs) {
eval {
print f($_)."\n";
};
print "Problem with entry $_: $@\n" if $@;
}

Lua
Lua
Lua may refer to:* Lua , a Roman goddess* Lua , a traditional Hawaiian martial art* Lua , a lightweight, extensible programming language* Lua , a single by the folk rock band Bright Eyes...

A Lua variant might look like this. Lua is compiled with Double precision
Double precision
In computing, double precision is a computer number format that occupies two adjacent storage locations in computer memory. A double-precision number, sometimes simply called a double, may be defined to be an integer, fixed point, or floating point .Modern computers with 32-bit storage locations...

 numbers by default, but any other format is possible.

function f(x)
return math.abs(x)^0.5 + 5*x^3
end

t = {}

for i=1,11 do
table.insert(t, io.read)
end

for i=#t,1,-1 do
local r = f(t[i])
if r > 400
then print("TOO LARGE")
else print(r)
end
end

R
R (programming language)
R is a programming language and software environment for statistical computing and graphics. The R language is widely used among statisticians for developing statistical software, and R is widely used for statistical software development and data analysis....

/S-PLUS
S-PLUS
S-PLUS is a commercial implementation of the S programming language sold by TIBCO Software Inc..It features object-oriented programming capabilities and advanced analytical algorithms.-Historical timeline:...

In R/Splus the user is alerted of an overflow by NaN value. Three of many possible implementations are
  1. without an assignment

(function(t) sqrt(abs(t))+5*t^3)(rev(scan(nmax=11)))
  1. with an assignment

sqrt(abs(S <- rev(scan(nmax=11))))+5*S^3
  1. as a routine

tpk <- function(S = scan(nmax=11), t=rev(S)) sqrt(abs(t))+5*t^3

The last implementation makes use of the lazy evaluation mechanism of R for default values of parameters: t is evaluated only the first time it is used in a computation, after which t is well defined.

Bash
Bash
Bash is a Unix shell written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell . Released in 1989, it has been distributed widely as the shell for the GNU operating system and as the default shell on Linux, Mac OS X and Darwin...

The following works with and outputs (rounded-off) integers only:


f {
echo "sqrt(${1#-}) + 5 * $1 ^ 3" | bc
}

array=
for i in {0..10}; do
read array[n]
done

for ((i=${#array[@]}-1; i>=0; --i)); do
let x=$(f ${array[$i]})
(( x > 400 )) && echo 'TOO LARGE' || echo $x
done


Although external programs can be used for unavailable (complex) functions, Bash is inherently incapable of floating-point arithmetic comparison.

Scheme
Scheme
Scheme may refer to:* Scheme , a minimalist, multi-paradigm dialect of Lisp* Scheme , a concept in algebraic geometry* Scheme , a figure of speech that changes a sentence's structure-See also:...

The following is tested with Chicken Scheme.


(define (read-values n)
(if (zero? n)
'
(cons (string->number (read-line))
(read-values (- n 1)))))

(define (f x)
(+ (sqrt (abs x)) (* 5 x x x)))

(for-each
(lambda (val)
(let ((result (f val)))
(print
(if (> result 400)
"TOO LARGE"
result))))
(reverse (read-values 11)))

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK