Pular para o conteúdo

Conheça Walt Disney World

Trabb Pardo–Knuth algorithm

The Trabb Pardo–Knuth algorithm is a 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 trivial program which 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.

The simpler Hello world program has been used for much the same purpose.

Contents

The algorithm

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

ALGOL 60

   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.

C

#include <stdio.h>
#include <math.h>
 
#define N 11
 
double vals[N];
 
double f(double x) {
        return sqrt(fabs(x)) + 5*x*x*x;
}
 
int main() {
        int i;
 
        for(i = 0; i < N; ++i)
                scanf("%lf", &vals[i]);
 
        for(i = N-1; i >= 0; --i) {
                double x = f(vals[i]);
                if(x > 400)
                        printf("TOO LARGE\n");
                else
                        printf("%.3f\n", x);
        }
 
        return 0;
}

Haskell

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

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

The Ruby version takes advantage of some of its distinctive 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 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 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

A Perl version using exceptions might look like this:

use feature 'say';
 
sub f {
  sqrt(abs($_[0])) + 5*$_[0]**3
}
 
for (1..11) {
  push @inputs, scalar <>
}
 
for (reverse @inputs) {
  eval { say f($_) } or say "Problem with entry $_: $@"
}

Lua

A Lua variant might look like this. Lua is compiled with Double precision 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/S-PLUS

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

# without an assignment
(function(t) sqrt(abs(t))+5*t^3)(rev(scan(nmax=11))) 
 
# with an assignment
sqrt(abs(S <- rev(scan(nmax=11))))+5*S^3 
 
# 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

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

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)))

References

  • "The Early Development of Programming Languages" in A History of Computing in the Twentieth Century, New York, Academic Press, 1980. ISBN 0-12-491650-3 (Reprinted in Knuth, Donald E., et al., Selected Papers on Computer Languages, Stanford, CA, CSLI, 2003. ISBN 1-57586-382-0)

External links

Personal tools
  • Log in / create account
Namespaces

Variants
Actions
Navigation
Toolbox
Print/export
Languages