The SML Program: tpk.sml

  1 (*  tpk.sml -- Knuth's TPK program in Standard ML  *)
  2 let
  3   (*  define the function f(x) = sqrt(|x|) + 5*x**3  *)
  4   fun f (x) = Real.Math.sqrt (abs x) + 5.0 * (Real.Math.pow (x, 3.0));
  5 
  6   (*  define an auxiliary print function *)
  7   fun pr (f) =
  8      print ((if f>400.0 then " too large" else Real.toString f)^"\n");
  9 
 10   (*  define an auxiliary function to read real numbers; one per line *)
 11   fun read () =
 12      Option.valOf (Real.fromString (TextIO.inputLine TextIO.stdIn));
 13 
 14   (*  declare and initialize the values of the array "A" *)
 15   val A = Array.tabulate (11, fn _ => read ());
 16 
 17   val i = ref 10;
 18 in
 19   while !i>=0 do (pr (f (Array.sub (A, !i))); i:= !i - 1)
 20 end;
 21 
 22 
 23 (*  Reformulation of TPK in a "functional" way.  *)
 24 local
 25    fun f (x) = Real.Math.sqrt (abs x) + 5.0 * (Real.Math.pow (x, 3.0));
 26    fun p (x) = x<400.0
 27 in
 28    fun tpk (l) = List.filter p (List.map f (List.rev l));
 29 end;