Standard ML of New Jersey (SML/NJ)

Implementation of programming language Standard ML

Standard ML of New Jersey (SML/NJ) is a compiler and programming environment for Standard ML. It includes an interactive interpreter.

Examples:

Hello, World!:

Example for versions MLton, Moscow ML 2, SML/NJ 110

print is a built-in function defined with the following type:

string -> unit

This means that it takes 1 string as a parameter, and returns the unit type, ().

print "Hello World\n";

Factorial:

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;

Fibonacci numbers:

Example for versions SML/NJ 110

This example uses straightforward recursive solution. The print function prints strings. The ^ operator concatenates strings. The Int.toString function converts integers into strings.

fun fibonacci n =
  if n < 3 then
    1
  else
    fibonacci (n-1) + fibonacci (n-2)

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

CamelCase:

Example for versions SML/NJ 110
val text = valOf (TextIO.inputLine TextIO.stdIn);
fun capitalize s = let
  val (x::xs) = explode s
in
  implode (Char.toUpper x :: map Char.toLower xs)
end;
val result = concat (map capitalize (String.tokens (not o Char.isAlpha) text));
print (result ^ "\n");