Compiler project
Structures, Signatures and Functors in SML

Sven-Olof Nyström

Uppsala University

Links

<http://www.smlnj.org/doc/literature.html>

Tofte: Essentials of Standard ML Modules

(The page also contains links to other tutorials)

Use of a structure

TextIO.print "Hello\n";

TextIO is a structure that defines the function print.

Structures

A structure is defined as follows:

structure Name = struct
  Definitions
end

Example:

structure foo = struct
    type t = string
    val say = fn x => TextIO.print x
end

Call

foo.say "hej";

Signatures

Give the interface of a structure.

signature NAME = sig
    DECLARATIONS
end

Signatures, example

signature bar = sig
    type t
    val say : t -> unit
end

Signatures, cont

To say that the structure foo implements the signature bar:

structure foo:bar = struct
    type t = string
    val say = fn x => TextIO.print x
    val hello = fn ()
	=> TextIO.print "hello/n"
end
foo.say "hej"

is OK,

but not foo.hello()

(not part of the signature)

Note that we can pass a string as argument to `say' even though the signature only says that `say' expects an argument of the (unspecified) type t.

Functors

Build structures from structures.

   functor FunctorName (ParamName : SigName)
     = struct
         ...
       end;

To make a structure, we do as follows:

   structure ResultStructure
        = FunctorName (ArgumentStructure)

This builds a new structure with the argument structure. This works provided the types and signatures match up.

Functors, example

Example with functors: func.sml.

- SumInt.f([1,2,3]);
val it = 6 : addgroup.G

- SumString.f(["hej","hopp"]);
val it = "hejhopp" : stringgroup.G