Standard ML

Appeared in:
1983
Influenced:
Paradigm:
Typing discipline:
File extensions:
.sml
Versions and implementations (Collapse all | Expand all):
Programming language

Based on ML, Standard ML is a safe, modular, strict, functional, polymorphic programming language with compile-time type checking and type inference, garbage collection, exception handling, immutable data types and updatable references, abstract data types, and parametric modules. It has efficient implementations and a formal definition with a proof of soundness.

Elements of syntax:

Nestable comments (* *)
Case-sensitivity Yes
Variable identifier regexp [_a-zA-Z0-9']+
Function identifier regexp [_a-zA-Z0-9']+
Variable declaration with assignment val variable = value {toplevel} or let val variable = value in ... end {local scope}
Block ( ... )
Deep equality = (only for eqtypes)
Deep inequality <> (only for eqtypes)
Comparison < > <= >=
Function definition fun f p1 p2 ... = ... or val f = fn p1 => fn p2 ... => ...
Function call f a b ...
Function call with no parameters f ()
Sequence ;
If - then if condition then ... else ()
If - then - else if condition then ... else ...
Loop forever while true do ( ... )
While condition do while condition do ( ... )

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