Standard ML Programming


Since this book is far from being complete this is just a list of the existing pages.

  1. Types
  2. Expressions
  3. Examples and Exercises
  4. Solutions

About Standard MLEdit

Standard ML (SML) belongs to the ML family of programming languages. Like other members of this family (such as OCaml), it is characterized by strong, static typing, strict evaluation, and type inference. The current standard dates from 1997; it supersedes an earlier standard from 1990.

Syntax examplesEdit

The following code snippet creates a function factorial that accepts a non-negative integer n and returns its factorial.

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

The following code snippet creates a function gray_code that accepts an integer n, and returns a list of all distinct n-character strings of 0s and 1s, in Gray code order (such that any two successive elements of the list differ in exactly one character). It then uses this function to generate the list gray_code_3 equal to ["000", "001", "011", "010", "110", "111", "101", "100"].

fun gray_code n =
  if n < 1
  then "" :: nil
  else let val prev = gray_code (n-1)
        in (map (fn s => "0" ^ s) prev) @ (rev (map (fn s => "1" ^ s) prev))
val gray_code_3 = gray_code 3

In the above code listings, reserved words are shown in boldface, and built-in identifiers (i.e., identifiers declared in the Standard ML Basis) are shown in italics.

Getting startedEdit

To get started with Standard ML, one needs a compiler. Most compilers compile directly to machine code; however, unlike (for example) a typical C compiler, several SML compilers, such as Standard ML of New Jersey (SMLNJ), can accept SML input interactively, compiling and evaluating code as it is entered. This can be very convenient when first getting started with SML. One important note: the code snippets in this book are presented in the form they would take in a normal SML program that is first saved as a file. To run them interactively in SMLNJ, a semicolon should be appended, to inform SMLNJ that it can evaluate the code so far; for example, the factorial example above would be written thus:

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


Standard ML has a particularly strong static type system. Unlike many languages, it does not have subtypes ("is-a" relationships) or implicit casts between types.

Types in Standard ML are discussed more fully in the Types chapter.

External resourcesEdit