<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <META name="GENERATOR" content="hevea 1.06-7 of 2001-11-14"> <TITLE> The module system </TITLE> </HEAD> <BODY TEXT=black BGCOLOR=white> <A HREF="manual003.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A> <A HREF="manual005.html"><IMG SRC ="next_motif.gif" ALT="Next"></A> <HR> <TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%"> <TR><TD BGCOLOR="#2de52d"><DIV ALIGN=center><TABLE> <TR><TD><A NAME="htoc12"><B><FONT SIZE=6>Chapter 2</FONT></B></A></TD> <TD WIDTH="100%" ALIGN=center><B><FONT SIZE=6>The module system</FONT></B></TD> </TR></TABLE></DIV></TD> </TR></TABLE> <A NAME="c:moduleexamples"></A> <BR> This chapter introduces the module system of Objective Caml.<BR> <BR> <TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%"> <TR><TD BGCOLOR="#66ff66"><DIV ALIGN=center><TABLE> <TR><TD><A NAME="htoc13"><B><FONT SIZE=5>2.1</FONT></B></A></TD> <TD WIDTH="100%" ALIGN=center><B><FONT SIZE=5>Structures</FONT></B></TD> </TR></TABLE></DIV></TD> </TR></TABLE> <BR> A primary motivation for modules is to package together related definitions (such as the definitions of a data type and associated operations over that type) and enforce a consistent naming scheme for these definitions. This avoids running out of names or accidentally confusing names. Such a package is called a <EM>structure</EM> and is introduced by the <TT>struct</TT>...<TT>end</TT> construct, which contains an arbitrary sequence of definitions. The structure is usually given a name with the <TT>module</TT> binding. Here is for instance a structure packaging together a type of priority queues and their operations: <PRE><FONT COLOR=black>#<FONT COLOR=blue>module PrioQueue = struct type priority = int type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue let empty = Empty let rec insert queue prio elt = match queue with Empty -> Node(prio, elt, Empty, Empty) | Node(p, e, left, right) -> if prio <= p then Node(prio, elt, insert right p e, left) else Node(p, e, insert right prio elt, left) exception Queue_is_empty let rec remove_top = function Empty -> raise Queue_is_empty | Node(prio, elt, left, Empty) -> left | Node(prio, elt, Empty, right) -> right | Node(prio, elt, (Node(lprio, lelt, _, _) as left), (Node(rprio, relt, _, _) as right)) -> if lprio <= rprio then Node(lprio, lelt, remove_top left, right) else Node(rprio, relt, left, remove_top right) let extract = function Empty -> raise Queue_is_empty | Node(prio, elt, _, _) as queue -> (prio, elt, remove_top queue) end;; <FONT COLOR=maroon>module PrioQueue : sig type priority = int and 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue val empty : 'a queue val insert : 'a queue -> priority -> 'a -> 'a queue exception Queue_is_empty val remove_top : 'a queue -> 'a queue val extract : 'a queue -> priority * 'a * 'a queue end </FONT></FONT></FONT></PRE> Outside the structure, its components can be referred to using the ``dot notation'', that is, identifiers qualified by a structure name. For instance, <TT>PrioQueue.insert</TT> in a value context is the function <TT>insert</TT> defined inside the structure <TT>PrioQueue</TT>. Similarly, <TT>PrioQueue.queue</TT> in a type context is the type <TT>queue</TT> defined in <TT>PrioQueue</TT>. <PRE><FONT COLOR=black>#<FONT COLOR=blue>PrioQueue.insert PrioQueue.empty 1 "hello";; <FONT COLOR=maroon>- : string PrioQueue.queue = PrioQueue.Node (1, "hello", PrioQueue.Empty, PrioQueue.Empty) </FONT></FONT></FONT></PRE> <TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%"> <TR><TD BGCOLOR="#66ff66"><DIV ALIGN=center><TABLE> <TR><TD><A NAME="htoc14"><B><FONT SIZE=5>2.2</FONT></B></A></TD> <TD WIDTH="100%" ALIGN=center><B><FONT SIZE=5>Signatures</FONT></B></TD> </TR></TABLE></DIV></TD> </TR></TABLE> <BR> Signatures are interfaces for structures. A signature specifies which components of a structure are accessible from the outside, and with which type. It can be used to hide some components of a structure (e.g. local function definitions) or export some components with a restricted type. For instance, the signature below specifies the three priority queue operations <TT>empty</TT>, <TT>insert</TT> and <TT>extract</TT>, but not the auxiliary function <TT>remove_top</TT>. Similarly, it makes the <TT>queue</TT> type abstract (by not providing its actual representation as a concrete type). <PRE><FONT COLOR=black>#<FONT COLOR=blue>module type PRIOQUEUE = sig type priority = int (* still concrete *) type 'a queue (* now abstract *) val empty : 'a queue val insert : 'a queue -> int -> 'a -> 'a queue val extract : 'a queue -> int * 'a * 'a queue exception Queue_is_empty end;; <FONT COLOR=maroon>module type PRIOQUEUE = sig type priority = int and 'a queue val empty : 'a queue val insert : 'a queue -> int -> 'a -> 'a queue val extract : 'a queue -> int * 'a * 'a queue exception Queue_is_empty end </FONT></FONT></FONT></PRE> Restricting the <TT>PrioQueue</TT> structure by this signature results in another view of the <TT>PrioQueue</TT> structure where the <TT>remove_top</TT> function is not accessible and the actual representation of priority queues is hidden: <PRE><FONT COLOR=black>#<FONT COLOR=blue>module AbstractPrioQueue = (PrioQueue : PRIOQUEUE);; <FONT COLOR=maroon>module AbstractPrioQueue : PRIOQUEUE <FONT COLOR=black>#<FONT COLOR=blue><U>AbstractPrioQueue.remove_top</U>;; <FONT COLOR=maroon>Unbound value AbstractPrioQueue.remove_top <FONT COLOR=black>#<FONT COLOR=blue>AbstractPrioQueue.insert AbstractPrioQueue.empty 1 "hello";; <FONT COLOR=maroon>- : string AbstractPrioQueue.queue = <abstr> </FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></PRE> The restriction can also be performed during the definition of the structure, as in <PRE> module PrioQueue = (struct ... end : PRIOQUEUE);; </PRE>An alternate syntax is provided for the above: <PRE> module PrioQueue : PRIOQUEUE = struct ... end;; </PRE> <TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%"> <TR><TD BGCOLOR="#66ff66"><DIV ALIGN=center><TABLE> <TR><TD><A NAME="htoc15"><B><FONT SIZE=5>2.3</FONT></B></A></TD> <TD WIDTH="100%" ALIGN=center><B><FONT SIZE=5>Functors</FONT></B></TD> </TR></TABLE></DIV></TD> </TR></TABLE> <BR> Functors are ``functions'' from structures to structures. They are used to express parameterized structures: a structure <I>A</I> parameterized by a structure <I>B</I> is simply a functor <I>F</I> with a formal parameter <I>B</I> (along with the expected signature for <I>B</I>) which returns the actual structure <I>A</I> itself. The functor <I>F</I> can then be applied to one or several implementations <I>B</I><SUB><FONT SIZE=2>1</FONT></SUB> ...<I>B</I><SUB><FONT SIZE=2><I>n</I></FONT></SUB> of <I>B</I>, yielding the corresponding structures <I>A</I><SUB><FONT SIZE=2>1</FONT></SUB> ...<I>A</I><SUB><FONT SIZE=2><I>n</I></FONT></SUB>.<BR> <BR> For instance, here is a structure implementing sets as sorted lists, parameterized by a structure providing the type of the set elements and an ordering function over this type (used to keep the sets sorted): <PRE><FONT COLOR=black>#<FONT COLOR=blue>type comparison = Less | Equal | Greater;; <FONT COLOR=maroon>type comparison = Less | Equal | Greater <FONT COLOR=black>#<FONT COLOR=blue>module type ORDERED_TYPE = sig type t val compare: t -> t -> comparison end;; <FONT COLOR=maroon>module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end <FONT COLOR=black>#<FONT COLOR=blue>module Set = functor (Elt: ORDERED_TYPE) -> struct type element = Elt.t type set = element list let empty = [] let rec add x s = match s with [] -> [x] | hd::tl -> match Elt.compare x hd with Equal -> s (* x is already in s *) | Less -> x :: s (* x is smaller than all elements of s *) | Greater -> hd :: add x tl let rec member x s = match s with [] -> false | hd::tl -> match Elt.compare x hd with Equal -> true (* x belongs to s *) | Less -> false (* x is smaller than all elements of s *) | Greater -> member x tl end;; <FONT COLOR=maroon>module Set : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t and set = element list val empty : 'a list val add : Elt.t -> Elt.t list -> Elt.t list val member : Elt.t -> Elt.t list -> bool end </FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></PRE> By applying the <TT>Set</TT> functor to a structure implementing an ordered type, we obtain set operations for this type: <PRE><FONT COLOR=black>#<FONT COLOR=blue>module OrderedString = struct type t = string let compare x y = if x = y then Equal else if x < y then Less else Greater end;; <FONT COLOR=maroon>module OrderedString : sig type t = string val compare : 'a -> 'a -> comparison end <FONT COLOR=black>#<FONT COLOR=blue>module StringSet = Set(OrderedString);; <FONT COLOR=maroon>module StringSet : sig type element = OrderedString.t and set = element list val empty : 'a list val add : OrderedString.t -> OrderedString.t list -> OrderedString.t list val member : OrderedString.t -> OrderedString.t list -> bool end <FONT COLOR=black>#<FONT COLOR=blue>StringSet.member "bar" (StringSet.add "foo" StringSet.empty);; <FONT COLOR=maroon>- : bool = false </FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></PRE> <TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%"> <TR><TD BGCOLOR="#66ff66"><DIV ALIGN=center><TABLE> <TR><TD><A NAME="htoc16"><B><FONT SIZE=5>2.4</FONT></B></A></TD> <TD WIDTH="100%" ALIGN=center><B><FONT SIZE=5>Functors and type abstraction</FONT></B></TD> </TR></TABLE></DIV></TD> </TR></TABLE> <BR> As in the <TT>PrioQueue</TT> example, it would be good style to hide the actual implementation of the type <TT>set</TT>, so that users of the structure will not rely on sets being lists, and we can switch later to another, more efficient representation of sets without breaking their code. This can be achieved by restricting <TT>Set</TT> by a suitable functor signature: <PRE><FONT COLOR=black>#<FONT COLOR=blue>module type SETFUNCTOR = functor (Elt: ORDERED_TYPE) -> sig type element = Elt.t (* concrete *) type set (* abstract *) val empty : set val add : element -> set -> set val member : element -> set -> bool end;; <FONT COLOR=maroon>module type SETFUNCTOR = functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t and set val empty : set val add : element -> set -> set val member : element -> set -> bool end <FONT COLOR=black>#<FONT COLOR=blue>module AbstractSet = (Set : SETFUNCTOR);; <FONT COLOR=maroon>module AbstractSet : SETFUNCTOR <FONT COLOR=black>#<FONT COLOR=blue>module AbstractStringSet = AbstractSet(OrderedString);; <FONT COLOR=maroon>module AbstractStringSet : sig type element = OrderedString.t and set = AbstractSet(OrderedString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end <FONT COLOR=black>#<FONT COLOR=blue>AbstractStringSet.add "gee" AbstractStringSet.empty;; <FONT COLOR=maroon>- : AbstractStringSet.set = <abstr> </FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></PRE> In an attempt to write the type constraint above more elegantly, one may wish to name the signature of the structure returned by the functor, then use that signature in the constraint: <PRE><FONT COLOR=black>#<FONT COLOR=blue>module type SET = sig type element type set val empty : set val add : element -> set -> set val member : element -> set -> bool end;; <FONT COLOR=maroon>module type SET = sig type element and set val empty : set val add : element -> set -> set val member : element -> set -> bool end <FONT COLOR=black>#<FONT COLOR=blue>module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);; <FONT COLOR=maroon>module WrongSet : functor (Elt : ORDERED_TYPE) -> SET <FONT COLOR=black>#<FONT COLOR=blue>module WrongStringSet = WrongSet(OrderedString);; <FONT COLOR=maroon>module WrongStringSet : sig type element = WrongSet(OrderedString).element and set = WrongSet(OrderedString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end <FONT COLOR=black>#<FONT COLOR=blue>WrongStringSet.add <U>"gee"</U> WrongStringSet.empty;; <FONT COLOR=maroon>This expression has type string but is here used with type WrongStringSet.element = WrongSet(OrderedString).element </FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></PRE> The problem here is that <TT>SET</TT> specifies the type <TT>element</TT> abstractly, so that the type equality between <TT>element</TT> in the result of the functor and <TT>t</TT> in its argument is forgotten. Consequently, <TT>WrongStringSet.element</TT> is not the same type as <TT>string</TT>, and the operations of <TT>WrongStringSet</TT> cannot be applied to strings. As demonstrated above, it is important that the type <TT>element</TT> in the signature <TT>SET</TT> be declared equal to <TT>Elt.t</TT>; unfortunately, this is impossible above since <TT>SET</TT> is defined in a context where <TT>Elt</TT> does not exist. To overcome this difficulty, Objective Caml provides a <TT>with type</TT> construct over signatures that allows to enrich a signature with extra type equalities: <PRE><FONT COLOR=black>#<FONT COLOR=blue>module AbstractSet = (Set : functor(Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));; <FONT COLOR=maroon>module AbstractSet : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t and set val empty : set val add : element -> set -> set val member : element -> set -> bool end </FONT></FONT></FONT></PRE> As in the case of simple structures, an alternate syntax is provided for defining functors and restricting their result: <PRE> module AbstractSet(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) = struct ... end;; </PRE> Abstracting a type component in a functor result is a powerful technique that provides a high degree of type safety, as we now illustrate. Consider an ordering over character strings that is different from the standard ordering implemented in the <TT>OrderedString</TT> structure. For instance, we compare strings without distinguishing upper and lower case. <PRE><FONT COLOR=black>#<FONT COLOR=blue>module NoCaseString = struct type t = string let compare s1 s2 = OrderedString.compare (String.lowercase s1) (String.lowercase s2) end;; <FONT COLOR=maroon>module NoCaseString : sig type t = string val compare : string -> string -> comparison end <FONT COLOR=black>#<FONT COLOR=blue>module NoCaseStringSet = AbstractSet(NoCaseString);; <FONT COLOR=maroon>module NoCaseStringSet : sig type element = NoCaseString.t and set = AbstractSet(NoCaseString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end <FONT COLOR=black>#<FONT COLOR=blue>NoCaseStringSet.add "FOO" <U>AbstractStringSet.empty</U>;; <FONT COLOR=maroon>This expression has type AbstractStringSet.set = AbstractSet(OrderedString).set but is here used with type NoCaseStringSet.set = AbstractSet(NoCaseString).set </FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></FONT></PRE> Notice that the two types <TT>AbstractStringSet.set</TT> and <TT>NoCaseStringSet.set</TT> are not compatible, and values of these two types do not match. This is the correct behavior: even though both set types contain elements of the same type (strings), both are built upon different orderings of that type, and different invariants need to be maintained by the operations (being strictly increasing for the standard ordering and for the case-insensitive ordering). Applying operations from <TT>AbstractStringSet</TT> to values of type <TT>NoCaseStringSet.set</TT> could give incorrect results, or build lists that violate the invariants of <TT>NoCaseStringSet</TT>.<BR> <BR> <TABLE CELLPADDING=0 CELLSPACING=0 WIDTH="100%"> <TR><TD BGCOLOR="#66ff66"><DIV ALIGN=center><TABLE> <TR><TD><A NAME="htoc17"><B><FONT SIZE=5>2.5</FONT></B></A></TD> <TD WIDTH="100%" ALIGN=center><B><FONT SIZE=5>Modules and separate compilation</FONT></B></TD> </TR></TABLE></DIV></TD> </TR></TABLE> <BR> All examples of modules so far have been given in the context of the interactive system. However, modules are most useful for large, batch-compiled programs. For these programs, it is a practical necessity to split the source into several files, called compilation units, that can be compiled separately, thus minimizing recompilation after changes.<BR> <BR> In Objective Caml, compilation units are special cases of structures and signatures, and the relationship between the units can be explained easily in terms of the module system. A compilation unit <I>a</I> comprises two files: <UL><LI> the implementation file <I>a</I><TT>.ml</TT>, which contains a sequence of definitions, analogous to the inside of a <TT>struct</TT>...<TT>end</TT> construct; <LI>the interface file <I>a</I><TT>.mli</TT>, which contains a sequence of specifications, analogous to the inside of a <TT>sig</TT>...<TT>end</TT> construct. </UL> Both files define a structure named <I>A</I> (same name as the base name <I>a</I> of the two files, with the first letter capitalized), as if the following definition was entered at top-level: <PRE> module <I>A</I>: sig (* contents of file <I>a</I>.mli *) end = struct (* contents of file <I>a</I>.ml *) end;; </PRE> The files defining the compilation units can be compiled separately using the <TT>ocamlc -c</TT> command (the <TT>-c</TT> option means ``compile only, do not try to link''); this produces compiled interface files (with extension <TT>.cmi</TT>) and compiled object code files (with extension <TT>.cmo</TT>). When all units have been compiled, their <TT>.cmo</TT> files are linked together using the <TT>ocaml</TT> command. For instance, the following commands compile and link a program composed of two compilation units <TT>aux</TT> and <TT>main</TT>: <PRE> $ ocamlc -c aux.mli # produces aux.cmi $ ocamlc -c aux.ml # produces aux.cmo $ ocamlc -c main.mli # produces main.cmi $ ocamlc -c main.ml # produces main.cmo $ ocamlc -o theprogram aux.cmo main.cmo </PRE>The program behaves exactly as if the following phrases were entered at top-level: <PRE> module Aux: sig (* contents of aux.mli *) end = struct (* contents of aux.ml *) end;; module Main: sig (* contents of main.mli *) end = struct (* contents of main.ml *) end;; </PRE> In particular, <TT>Main</TT> can refer to <TT>Aux</TT>: the definitions and declarations contained in <TT>main.ml</TT> and <TT>main.mli</TT> can refer to definition in <TT>aux.ml</TT>, using the <TT>Aux.</TT><I>ident</I> notation, provided these definitions are exported in <TT>aux.mli</TT>.<BR> <BR> The order in which the <TT>.cmo</TT> files are given to <TT>ocaml</TT> during the linking phase determines the order in which the module definitions occur. Hence, in the example above, <TT>Aux</TT> appears first and <TT>Main</TT> can refer to it, but <TT>Aux</TT> cannot refer to <TT>Main</TT>.<BR> <BR> Notice that only top-level structures can be mapped to separately-compiled files, but not functors nor module types. However, all module-class objects can appear as components of a structure, so the solution is to put the functor or module type inside a structure, which can then be mapped to a file. <BR> <BR> <HR> <A HREF="manual003.html"><IMG SRC ="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC ="contents_motif.gif" ALT="Contents"></A> <A HREF="manual005.html"><IMG SRC ="next_motif.gif" ALT="Next"></A> </BODY> </HTML>