Standard ML


Standard ML is a general-purpose, high-level, modular, functional programming language with compile-time type checking and type inference. It is popular for writing compilers, for programming language research, and for developing theorem provers.
Standard ML is a modern dialect of ML, the language used in the Logic for Computable Functions theorem-proving project. It is distinctive among widely used languages in that it has a formal specification, given as typing rules and operational semantics in The Definition of Standard ML, originally released in 1990, with a second and final revision being released in 1997.

Language

Standard ML is a functional programming language with some impure features. Programs written in Standard ML consist of expressions in contrast to statements or commands, although some expressions of type unit are only evaluated for their side-effects.

Functions

Like all functional languages, a key feature of Standard ML is the function, which is used for abstraction. The factorial function can be expressed as follows:

fun factorial n =
if n = 0 then 1 else n * factorial

Type inference

An SML compiler must infer the static type without user-supplied type annotations. It has to deduce that is only used with integer expressions, and must therefore itself be an integer, and that all terminal expressions are integer expressions.

Declarative definitions

The same function can be expressed with clausal function definitions where the if-''then-else'' conditional is replaced with templates of the factorial function evaluated for specific values:

fun factorial 0 = 1
| factorial n = n * factorial

Imperative definitions

or iteratively:

fun factorial n = let val i = ref n and acc = ref 1 in
while !i > 0 do ; !acc
end

Lambda functions

or as a lambda function:

val rec factorial = fn 0 => 1 | n => n * factorial

Here, the keyword introduces a binding of an identifier to a value, introduces an anonymous function, and allows the definition to be self-referential.

Local definitions

The encapsulation of an invariant-preserving tail-recursive tight loop with one or more accumulator parameters within an invariant-free outer function, as seen here, is a common idiom in Standard ML.
Using a local function, it can be rewritten in a more efficient tail-recursive style:

local
fun loop = acc
| loop = loop
in
fun factorial n = loop
end

Type synonyms

A type synonym is defined with the keyword. Here is a type synonym for points on a plane, and functions computing the distances between two points, and the area of a triangle with the given corners as per Heron's formula..

type loc = real * real
fun square = x * x
fun dist =
Math.sqrt + square )
fun heron = let
val x = dist a b
val y = dist b c
val z = dist a c
val s = / 2.0
in
Math.sqrt * * )
end

Algebraic datatypes

Standard ML provides strong support for algebraic datatypes. A data type can be thought of as a disjoint union of tuples. They are easy to define and easy to use, largely because of pattern matching, and most Standard ML implementations' pattern-exhaustiveness checking and pattern redundancy checking.
In object-oriented programming languages, a disjoint union can be expressed as class hierarchies. However, in contrast to class hierarchies, ADTs are closed. Thus, the extensibility of ADTs is orthogonal to the extensibility of class hierarchies. Class hierarchies can be extended with new subclasses which implement the same interface, while the functions of ADTs can be extended for the fixed set of constructors. See expression problem.
A datatype is defined with the keyword, as in:

datatype shape
= Circle of loc * real
| Square of loc * real
| Triangle of loc * loc * loc

Note that a type synonym cannot be recursive; datatypes are necessary to define recursive constructors.

Pattern matching

Patterns are matched in the order in which they are defined. C programmers can use tagged unions, dispatching on tag values, to do what ML does with datatypes and pattern matching. Nevertheless, while a C program decorated with appropriate checks will, in a sense, be as robust as the corresponding ML program, those checks will of necessity be dynamic; ML's static checks provide strong guarantees about the correctness of the program at compile time.
Function arguments can be defined as patterns as follows:

fun area = Math.pi * square r
| area = square s
| area = heron p

The so-called "clausal form" of function definition, where arguments are defined as patterns, is merely syntactic sugar for a case expression:

fun area shape = case shape of
Circle => Math.pi * square r
| Square => square s
| Triangle p => heron p

Exhaustiveness checking

Pattern-exhaustiveness checking will make sure that each constructor of the datatype is matched by at least one pattern.
The following pattern is not exhaustive:

fun center = c
| center ) =

There is no pattern for the case in the function. The compiler will issue a warning that the case expression is not exhaustive, and if a is passed to this function at runtime, will be raised.

Redundancy checking

The pattern in the second clause of the following function is redundant:

fun f ) = x + y
| f = 1.0
| f _ = 0.0

Any value that would match the pattern in the second clause would also match the pattern in the first clause, so the second clause is unreachable. Therefore, this definition as a whole exhibits redundancy, and causes a compile-time warning.
The following function definition is exhaustive and not redundant:

val hasCorners = fn => false | _ => true

If control gets past the first pattern, we know the shape must be either a or a. In either of those cases, we know the shape has corners, so we can return without discerning the actual shape.

Higher-order functions

Functions can consume functions as arguments:
fun map f =
Functions can produce functions as return values:
fun constant k =
Functions can also both consume and produce functions:
fun compose =
The function from the basis library is one of the most commonly used higher-order functions in Standard ML:

fun map _ =
| map f = f x :: map f xs

A more efficient implementation with tail-recursive :

fun map f = List.rev o List.foldl

Exceptions

Exceptions are raised with the keyword and handled with the pattern matching construct. The exception system can implement non-local exit; this optimization technique is suitable for functions like the following.

local
exception Zero;
val p = fn => raise Zero | => a * b
in
fun prod xs = List.foldl p 1 xs handle Zero => 0
end

When is raised, control leaves the function altogether. Consider the alternative: the value 0 would be returned, it would be multiplied by the next integer in the list, the resulting value would be returned, and so on. The raising of the exception allows control to skip over the entire chain of frames and avoid the associated computation. Note the use of the underscore as a wildcard pattern.
The same optimization can be obtained with a tail call.

local
fun p a = 0
| p a = p xs
| p a = a
in
val prod = p 1
end

Module system

Standard ML's advanced module system allows programs to be decomposed into hierarchically organized structures of logically related type and value definitions. Modules provide not only namespace control but also abstraction, in the sense that they allow the definition of abstract data types. Three main syntactic constructs comprise the module system: signatures, structures and functors.

Signatures

A signature is an interface, usually thought of as a type for a structure; it specifies the names of all entities provided by the structure, the arity of each type component, the type of each value component, and the signature of each substructure. The definitions of type components are optional; type components whose definitions are hidden are abstract types.
For example, the signature for a queue may be:

signature QUEUE = sig
type 'a queue
exception QueueError;
val empty : 'a queue
val isEmpty : 'a queue -> bool
val singleton : 'a -> 'a queue
val fromList : 'a list -> 'a queue
val insert : 'a * 'a queue -> 'a queue
val peek : 'a queue -> 'a
val remove : 'a queue -> 'a * 'a queue
end

This signature describes a module that provides a polymorphic type,, and values that define basic operations on queues.

Structures

A structure is a module; it consists of a collection of types, exceptions, values and structures packaged together into a logical unit.
A queue structure can be implemented as follows:

structure TwoListQueue :> QUEUE = struct
type 'a queue = 'a list * 'a list
exception QueueError;
val empty =
fun isEmpty = true
| isEmpty _ = false
fun singleton a =
fun fromList a =
fun insert = singleton a
| insert =
fun peek = raise QueueError
| peek = List.hd outs
fun remove = raise QueueError
| remove =
| remove =
end

This definition declares that implements. Furthermore, the opaque ascription denoted by states that any types which are not defined in the signature should be abstract, meaning that the definition of a queue as a pair of lists is not visible outside the module. The structure implements all of the definitions in the signature.
The types and values in a structure can be accessed with "dot notation":

val q : string TwoListQueue.queue = TwoListQueue.empty
val q' = TwoListQueue.insert

Functors

A functor is a function from structures to structures; that is, a functor accepts one or more arguments, which are usually structures of a given signature, and produces a structure as its result. Functors are used to implement generic data structures and algorithms.
One popular algorithm for breadth-first search of trees makes use of queues. Here is a version of that algorithm parameterized over an abstract queue structure:

functor BFS = struct
datatype 'a tree = E | T of 'a * 'a tree * 'a tree
local
fun bfsQ q = if Q.isEmpty q then else search
and search = bfsQ q
| search = x :: bfsQ
and insert q a = Q.insert
in
fun bfs t = bfsQ
end
end
structure QueueBFS = BFS

Within, the representation of the queue is not visible. More concretely, there is no way to select the first list in the two-list queue, if that is indeed the representation being used. This data abstraction mechanism makes the breadth-first search truly agnostic to the queue's implementation. This is in general desirable; in this case, the queue structure can safely maintain any logical invariants on which its correctness depends behind the bulletproof wall of abstraction.

Code examples

Snippets of SML code are most easily studied by entering them into an interactive top-level.

Hello, world!

The following is a "Hello, World!" program:
hello.sml


print "Hello, world!\n";
sh


$ mlton hello.sml
$./hello
Hello, world!

Algorithms

Insertion sort

Insertion sort for can be expressed concisely as follows:

fun insert = | insert = sort x
and sort x = if x < h then @ t else h :: insert
val insertionsort = List.foldl insert

Mergesort

Here, the classic mergesort algorithm is implemented in three functions: split, merge and mergesort. Also note the absence of types, with the exception of the syntax and which signify lists. This code will sort lists of any type, so long as a consistent ordering function is defined. Using Hindley–Milner type inference, the types of all variables can be inferred, even complicated types such as that of the function.
Split
is implemented with a stateful closure which alternates between and, ignoring the input:

fun alternator = let val state = ref true
in fn a => !state before state := not end
fun split xs = List.partition xs

Merge
Merge uses a local function loop for efficiency. The inner is defined in terms of cases: when both lists are non-empty and when one list is empty.
This function merges two sorted lists into one sorted list. Note how the accumulator is built backwards, then reversed before being returned. This is a common technique, since is represented as a linked list; this technique requires more clock time, but the asymptotics are not worse.

fun merge cmp = xs
| merge cmp = let
fun loop = List.revAppend
| loop =
if cmp
then loop
else loop
in
loop
end

Mergesort
The main function:

fun ap f =
fun mergesort cmp =
| mergesort cmp =
| mergesort cmp xs = xs

Quicksort

Quicksort can be expressed as follows. is a closure that consumes an order operator.

infix <<
fun quicksort = let
fun part p = List.partition
fun sort =
| sort = join p
and join p = sort l @ p :: sort r
in
sort
end

Expression interpreter

Note the relative ease with which a small expression language can be defined and processed:

exception TyErr;
datatype ty = IntTy | BoolTy
fun unify = IntTy
| unify = BoolTy
| unify = raise TyErr
datatype exp
= True
| False
| Int of int
| Not of exp
| Add of exp * exp
| If of exp * exp * exp
fun infer True = BoolTy
| infer False = BoolTy
| infer = IntTy
| infer =
| infer =
| infer =
and assert e t = unify
fun eval True = True
| eval False = False
| eval = Int n
| eval = if eval e = True then False else True
| eval = of => Int )
| eval = eval
fun run e = handle TyErr => NONE

Example usage on well-typed and ill-typed expressions:

val SOME = run
val NONE = run

Arbitrary-precision integers

The module provides arbitrary-precision integer arithmetic. Moreover, integer literals may be used as arbitrary-precision integers without the programmer having to do anything.
The following program implements an arbitrary-precision factorial function:
fact.sml


fun fact n : IntInf.int = if n = 0 then 1 else n * fact ;
fun printLine str = TextIO.output ;
val = printLine ;
bash


$ mlton fact.sml
$./fact
6689502913449127057588118054090372586752746333138029810295671352301
6335572449629893668741652719849813081576378932140905525344085894081
21859898481114389650005964960521256960000000000000000000000000000

Partial application

Curried functions have many applications, such as eliminating redundant code. For example, a module may require functions of type, but it is more convenient to write functions of type where there is a fixed relationship between the objects of type and. A function of type can factor out this commonality. This is an example of the adapter pattern.
In this example, computes the numerical derivative of a given function at point :

- fun d delta f x = - f ) /
val d = fn : real -> -> real -> real

The type of indicates that it maps a "float" onto a function with the type. This allows us to partially apply arguments, known as currying. In this case, function can be specialised by partially applying it with the argument. A good choice for when using this algorithm is the cube root of the machine epsilon.

- val d' = d 1E~8;
val d' = fn : -> real -> real

The inferred type indicates that expects a function with the type as its first argument. We can compute an approximation to the derivative of at. The correct answer is.

- d' 3.0;
val it = 25.9999996644 : real

Libraries

Standard

The Basis Library has been standardized and ships with most implementations. It provides modules for trees, arrays, and other data structures, and input/output and system interfaces.

Third party

For numerical computing, a Matrix module exists, https://www.cs.cmu.edu/afs/cs/project/pscico/pscico/src/matrix/README.html.
For graphics, cairo-sml is an open source interface to the Cairo graphics library. For machine learning, a library for graphical models exists.

Implementations

Implementations of Standard ML include the following:
Standard
Derivative
Research
All of these implementations are open-source and freely available. Most are implemented themselves in Standard ML. There are no longer any commercial implementations; Harlequin, now defunct, once produced a commercial IDE and compiler called MLWorks which passed on to Xanalys and was later open-sourced after it was acquired by Ravenbrook Limited on April 26, 2013.

Major projects using SML

The IT University of Copenhagen's entire enterprise architecture is implemented in around 100,000 lines of SML, including staff records, payroll, course administration and feedback, student project management, and web-based self-service interfaces.
The proof assistants HOL4, Isabelle, LEGO, and Twelf are written in Standard ML. It is also used by compiler writers and integrated circuit designers such as ARM.