Factorial in Standard ML

Example for versions SML/NJ 110

This example shows the naive way to implement the factorial function. However, it is not tail recursive, since the recursive function call is not the only statement on the line. The ^ operator concatenates strings. The print function prints strings. The Int.toString function converts integers into strings.

fun factorial n =
    if n <= 1 then
      1
    else
      factorial (n-1) * n;

fun aux n =
  if n > 16 then
    ()
  else (
    print (Int.toString n ^ "! = " ^ Int.toString (factorial n) ^ "\n");
    aux (n + 1)
  );
aux 0;