The Objective Caml system
release 3.11
Documentation and user's manual
Xavier Leroy
(with Damien Doligez, Jacques Garrigue, Didier Rémy and Jérôme Vouillon)
November 26, 2008
 
Copyright © 2008 Institut National de Recherche en Informatique et en Automatique

This manual is also available in PDF. Postscript, DVI, plain text, as a bundle of HTML files, and as a bundle of Emacs Info files.

Contents

Foreword

This manual documents the release 3.11 of the Objective Caml system. It is organized as follows.

Conventions

Objective Caml runs on several operating systems. The parts of this manual that are specific to one operating system are presented as shown below:

Unix:   This is material specific to the Unix family of operating systems, including Linux and MacOS X.
Windows:   This is material specific to Microsoft Windows (2000, XP, Vista).

License

The Objective Caml system is copyright © 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Institut National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership rights to the Objective Caml system.

The Objective Caml system is open source and can be freely redistributed. See the file LICENSE in the distribution for licensing information.

The present documentation is copyright © 2008 Institut National de Recherche en Informatique et en Automatique (INRIA). The Objective Caml documentation and user's manual may be reproduced and distributed in whole or in part, subject to the following conditions:

Availability

The complete Objective Caml distribution can be accessed via the http://caml.inria.fr/Caml Web site. The http://caml.inria.fr/Caml Web site contains a lot of additional information on Objective Caml.

Part I
An introduction to Objective Caml

Chapter 1  The core language

This part of the manual is a tutorial introduction to the Objective Caml language. A good familiarity with programming in a conventional languages (say, Pascal or C) is assumed, but no prior exposure to functional languages is required. The present chapter introduces the core language. Chapter 3 deals with the object-oriented features, and chapter 2 with the module system.

1.1  Basics

For this overview of Caml, we use the interactive system, which is started by running ocaml from the Unix shell, or by launching the OCamlwin.exe application under Windows. This tutorial is presented as the transcript of a session with the interactive system: lines starting with # represent user input; the system responses are printed below, without a leading #.

Under the interactive system, the user types Caml phrases, terminated by ;;, in response to the # prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation. Phrases are either simple expressions, or let definitions of identifiers (either values or functions).

#1+2*3;;
- : int = 7
 
#let pi = 4.0 *. atan 1.0;;
val pi : float = 3.14159265358979312
 
#let square x = x *. x;;
val square : float -> float = <fun>
 
#square(sin pi) +. square(cos pi);;
- : float = 1.

The Caml system computes both the value and the type for each phrase. Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: + and * operate on integers, but +. and *. operate on floats.

#1.0 * 2;;
This expression has type float but is here used with type int

Recursive functions are defined with the let rec binding:

#let rec fib n =
   if n < 2 then n else fib(n-1) + fib(n-2);;
val fib : int -> int = <fun>
 
#fib 10;;
- : int = 55

1.2  Data types

In addition to integers and floating-point numbers, Caml offers the usual basic data types: booleans, characters, and character strings.

#(1 < 2) = false;;
- : bool = false
 
#'a';;
- : char = 'a'
 
#"Hello world";;
- : string = "Hello world"

Predefined data structures include tuples, arrays, and lists. General mechanisms for defining your own data structures are also provided. They will be covered in more details later; for now, we concentrate on lists. Lists are either given in extension as a bracketed list of semicolon-separated elements, or built from the empty list [] (pronounce “nil”) by adding elements in front using the :: (“cons”) operator.

#let l = ["is"; "a"; "tale"; "told"; "etc."];;
val l : string list = ["is"; "a"; "tale"; "told"; "etc."]
 
#"Life" :: l;;
- : string list = ["Life"; "is"; "a"; "tale"; "told"; "etc."]

As with all other Caml data structures, lists do not need to be explicitly allocated and deallocated from memory: all memory management is entirely automatic in Caml. Similarly, there is no explicit handling of pointers: the Caml compiler silently introduces pointers where necessary.

As with most Caml data structures, inspecting and destructuring lists is performed by pattern-matching. List patterns have the exact same shape as list expressions, with identifier representing unspecified parts of the list. As an example, here is insertion sort on a list:

#let rec sort lst =
   match lst with
     [] -> []
   | head :: tail -> insert head (sort tail)
 and insert elt lst =
   match lst with
     [] -> [elt]
   | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail
 ;;
val sort : 'a list -> 'a list = <fun>
val insert : 'a -> 'a list -> 'a list = <fun>
 
#sort l;;
- : string list = ["a"; "etc."; "is"; "tale"; "told"]

The type inferred for sort, 'a list -> 'a list, means that sort can actually apply to lists of any type, and returns a list of the same type. The type 'a is a type variable, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are polymorphic in Caml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.

#sort [6;2;5;3];;
- : int list = [2; 3; 5; 6]
 
#sort [3.14; 2.718];;
- : float list = [2.718; 3.14]

The sort function above does not modify its input list: it builds and returns a new list containing the same elements as the input list, in ascending order. There is actually no way in Caml to modify in-place a list once it is built: we say that lists are immutable data structures. Most Caml data structures are immutable, but a few (most notably arrays) are mutable, meaning that they can be modified in-place at any time.

1.3  Functions as values

Caml is a functional language: functions in the full mathematical sense are supported and can be passed around freely just as any other piece of data. For instance, here is a deriv function that takes any float function as argument and returns an approximation of its derivative function:

#let deriv f dx = function x -> (f(x +. dx) -. f(x)) /. dx;;
val deriv : (float -> float) -> float -> float -> float = <fun>
 
#let sin' = deriv sin 1e-6;;
val sin' : float -> float = <fun>
 
#sin' pi;;
- : float = -1.00000000013961143

Even function composition is definable:

#let compose f g = function x -> f(g(x));;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
 
#let cos2 = compose square cos;;
val cos2 : float -> float = <fun>

Functions that take other functions as arguments are called “functionals”, or “higher-order functions”. Functionals are especially useful to provide iterators or similar generic operations over a data structure. For instance, the standard Caml library provides a List.map functional that applies a given function to each element of a list, and returns the list of the results:

#List.map (function n -> n * 2 + 1) [0;1;2;3;4];;
- : int list = [1; 3; 5; 7; 9]

This functional, along with a number of other list and array functionals, is predefined because it is often useful, but there is nothing magic with it: it can easily be defined as follows.

#let rec map f l =
   match l with
     [] -> []
   | hd :: tl -> f hd :: map f tl;;
val map : ('a -> 'b) -> 'a list -> 'b list = <fun>

1.4  Records and variants

User-defined data structures include records and variants. Both are defined with the type declaration. Here, we declare a record type to represent rational numbers.

#type ratio = {num: int; denum: int};;
type ratio = { num : int; denum : int; }
 
#let add_ratio r1 r2 =
   {num = r1.num * r2.denum + r2.num * r1.denum;
    denum = r1.denum * r2.denum};;
val add_ratio : ratio -> ratio -> ratio = <fun>
 
#add_ratio {num=1; denum=3} {num=2; denum=5};;
- : ratio = {num = 11; denum = 15}

The declaration of a variant type lists all possible shapes for values of that type. Each case is identified by a name, called a constructor, which serves both for constructing values of the variant type and inspecting them by pattern-matching. Constructor names are capitalized to distinguish them from variable names (which must start with a lowercase letter). For instance, here is a variant type for doing mixed arithmetic (integers and floats):

#type number = Int of int | Float of float | Error;;
type number = Int of int | Float of float | Error

This declaration expresses that a value of type number is either an integer, a floating-point number, or the constant Error representing the result of an invalid operation (e.g. a division by zero).

Enumerated types are a special case of variant types, where all alternatives are constants:

#type sign = Positive | Negative;;
type sign = Positive | Negative
 
#let sign_int n = if n >= 0 then Positive else Negative;;
val sign_int : int -> sign = <fun>

To define arithmetic operations for the number type, we use pattern-matching on the two numbers involved:

#let add_num n1 n2 =
   match (n1, n2) with
     (Int i1, Int i2) ->
       (* Check for overflow of integer addition *)
       if sign_int i1 = sign_int i2 && sign_int(i1 + i2) <> sign_int i1
       then Float(float i1 +. float i2)
       else Int(i1 + i2)
   | (Int i1, Float f2) -> Float(float i1 +. f2)
   | (Float f1, Int i2) -> Float(f1 +. float i2)
   | (Float f1, Float f2) -> Float(f1 +. f2)
   | (Error, _) -> Error
   | (_, Error) -> Error;;
val add_num : number -> number -> number = <fun>
 
#add_num (Int 123) (Float 3.14159);;
- : number = Float 126.14159

The most common usage of variant types is to describe recursive data structures. Consider for example the type of binary trees:

#type 'a btree = Empty | Node of 'a * 'a btree * 'a btree;;
type 'a btree = Empty | Node of 'a * 'a btree * 'a btree

This definition reads as follow: a binary tree containing values of type 'a (an arbitrary type) is either empty, or is a node containing one value of type 'a and two subtrees containing also values of type 'a, that is, two 'a btree.

Operations on binary trees are naturally expressed as recursive functions following the same structure as the type definition itself. For instance, here are functions performing lookup and insertion in ordered binary trees (elements increase from left to right):

#let rec member x btree =
   match btree with
     Empty -> false
   | Node(y, left, right) ->
       if x = y then true else
       if x < y then member x left else member x right;;
val member : 'a -> 'a btree -> bool = <fun>
 
#let rec insert x btree =
   match btree with
     Empty -> Node(x, Empty, Empty)
   | Node(y, left, right) ->
       if x <= y then Node(y, insert x left, right)
                 else Node(y, left, insert x right);;
val insert : 'a -> 'a btree -> 'a btree = <fun>

1.5  Imperative features

Though all examples so far were written in purely applicative style, Caml is also equipped with full imperative features. This includes the usual while and for loops, as well as mutable data structures such as arrays. Arrays are either given in extension between [| and |] brackets, or allocated and initialized with the Array.create function, then filled up later by assignments. For instance, the function below sums two vectors (represented as float arrays) componentwise.

#let add_vect v1 v2 =
   let len = min (Array.length v1) (Array.length v2) in
   let res = Array.create len 0.0 in
   for i = 0 to len - 1 do
     res.(i) <- v1.(i) +. v2.(i)
   done;
   res;;
val add_vect : float array -> float array -> float array = <fun>
 
#add_vect [| 1.0; 2.0 |] [| 3.0; 4.0 |];;
- : float array = [|4.; 6.|]

Record fields can also be modified by assignment, provided they are declared mutable in the definition of the record type:

#type mutable_point = { mutable x: float; mutable y: float };;
type mutable_point = { mutable x : float; mutable y : float; }
 
#let translate p dx dy =
   p.x <- p.x +. dx; p.y <- p.y +. dy;;
val translate : mutable_point -> float -> float -> unit = <fun>
 
#let mypoint = { x = 0.0; y = 0.0 };;
val mypoint : mutable_point = {x = 0.; y = 0.}
 
#translate mypoint 1.0 2.0;;
- : unit = ()
 
#mypoint;;
- : mutable_point = {x = 1.; y = 2.}

Caml has no built-in notion of variable – identifiers whose current value can be changed by assignment. (The let binding is not an assignment, it introduces a new identifier with a new scope.) However, the standard library provides references, which are mutable indirection cells (or one-element arrays), with operators ! to fetch the current contents of the reference and := to assign the contents. Variables can then be emulated by let-binding a reference. For instance, here is an in-place insertion sort over arrays:

#let insertion_sort a =
   for i = 1 to Array.length a - 1 do
     let val_i = a.(i) in
     let j = ref i in
     while !j > 0 && val_i < a.(!j - 1) do
       a.(!j) <- a.(!j - 1);
       j := !j - 1
     done;
     a.(!j) <- val_i
   done;;
val insertion_sort : 'a array -> unit = <fun>

References are also useful to write functions that maintain a current state between two calls to the function. For instance, the following pseudo-random number generator keeps the last returned number in a reference:

#let current_rand = ref 0;;
val current_rand : int ref = {contents = 0}
 
#let random () =
   current_rand := !current_rand * 25713 + 1345;
   !current_rand;;
val random : unit -> int = <fun>

Again, there is nothing magic with references: they are implemented as a one-field mutable record, as follows.

#type 'a ref = { mutable contents: 'a };;
type 'a ref = { mutable contents : 'a; }
 
#let (!) r = r.contents;;
val ( ! ) : 'a ref -> 'a = <fun>
 
#let (:=) r newval = r.contents <- newval;;
val ( := ) : 'a ref -> 'a -> unit = <fun>

In some special cases, you may need to store a polymorphic function in a data structure, keeping its polymorphism. Without user-provided type annotations, this is not allowed, as polymorphism is only introduced on a global level. However, you can give explicitly polymorphic types to record fields.

#type idref = { mutable id: 'a. 'a -> 'a };;
type idref = { mutable id : 'a. 'a -> 'a; }
 
#let r = {id = fun x -> x};;
val r : idref = {id = <fun>}
 
#let g s = (s.id 1, s.id true);;
val g : idref -> int * bool = <fun>
 
#r.id <- (fun x -> print_string "called id\n"; x);;
- : unit = ()
 
#g r;;
called id
called id
- : int * bool = (1, true)

1.6  Exceptions

Caml provides exceptions for signalling and handling exceptional conditions. Exceptions can also be used as a general-purpose non-local control structure. Exceptions are declared with the exception construct, and signalled with the raise operator. For instance, the function below for taking the head of a list uses an exception to signal the case where an empty list is given.

#exception Empty_list;;
exception Empty_list
 
#let head l =
   match l with
     [] -> raise Empty_list
   | hd :: tl -> hd;;
val head : 'a list -> 'a = <fun>
 
#head [1;2];;
- : int = 1
 
#head [];;
Exception: Empty_list.

Exceptions are used throughout the standard library to signal cases where the library functions cannot complete normally. For instance, the List.assoc function, which returns the data associated with a given key in a list of (key, data) pairs, raises the predefined exception Not_found when the key does not appear in the list:

#List.assoc 1 [(0, "zero"); (1, "one")];;
- : string = "one"
 
#List.assoc 2 [(0, "zero"); (1, "one")];;
Exception: Not_found.

Exceptions can be trapped with the trywith construct:

#let name_of_binary_digit digit =
   try
     List.assoc digit [0, "zero"; 1, "one"]
   with Not_found ->
     "not a binary digit";;
val name_of_binary_digit : int -> string = <fun>
 
#name_of_binary_digit 0;;
- : string = "zero"
 
#name_of_binary_digit (-1);;
- : string = "not a binary digit"

The with part is actually a regular pattern-matching on the exception value. Thus, several exceptions can be caught by one trywith construct. Also, finalization can be performed by trapping all exceptions, performing the finalization, then raising again the exception:

#let temporarily_set_reference ref newval funct =
   let oldval = !ref in
   try
     ref := newval;
     let res = funct () in
     ref := oldval;
     res
   with x ->
     ref := oldval;
     raise x;;
val temporarily_set_reference : 'a ref -> 'a -> (unit -> 'b) -> 'b = <fun>

1.7  Symbolic processing of expressions

We finish this introduction with a more complete example representative of the use of Caml for symbolic processing: formal manipulations of arithmetic expressions containing variables. The following variant type describes the expressions we shall manipulate:

#type expression =
     Const of float
   | Var of string
   | Sum of expression * expression    (* e1 + e2 *)
   | Diff of expression * expression   (* e1 - e2 *)
   | Prod of expression * expression   (* e1 * e2 *)
   | Quot of expression * expression   (* e1 / e2 *)
 ;;
type expression =
    Const of float
  | Var of string
  | Sum of expression * expression
  | Diff of expression * expression
  | Prod of expression * expression
  | Quot of expression * expression

We first define a function to evaluate an expression given an environment that maps variable names to their values. For simplicity, the environment is represented as an association list.

#exception Unbound_variable of string;;
exception Unbound_variable of string
 
#let rec eval env exp =
   match exp with
     Const c -> c
   | Var v ->
       (try List.assoc v env with Not_found -> raise(Unbound_variable v))
   | Sum(f, g) -> eval env f +. eval env g
   | Diff(f, g) -> eval env f -. eval env g
   | Prod(f, g) -> eval env f *. eval env g
   | Quot(f, g) -> eval env f /. eval env g;;
val eval : (string * float) list -> expression -> float = <fun>
 
#eval [("x", 1.0); ("y", 3.14)] (Prod(Sum(Var "x", Const 2.0), Var "y"));;
- : float = 9.42

Now for a real symbolic processing, we define the derivative of an expression with respect to a variable dv:

#let rec deriv exp dv =
   match exp with
     Const c -> Const 0.0
   | Var v -> if v = dv then Const 1.0 else Const 0.0
   | Sum(f, g) -> Sum(deriv f dv, deriv g dv)
   | Diff(f, g) -> Diff(deriv f dv, deriv g dv)
   | Prod(f, g) -> Sum(Prod(f, deriv g dv), Prod(deriv f dv, g))
   | Quot(f, g) -> Quot(Diff(Prod(deriv f dv, g), Prod(f, deriv g dv)),
                        Prod(g, g))
 ;;
val deriv : expression -> string -> expression = <fun>
 
#deriv (Quot(Const 1.0, Var "x")) "x";;
- : expression =
Quot (Diff (Prod (Const 0., Var "x"), Prod (Const 1., Const 1.)),
 Prod (Var "x", Var "x"))

1.8  Pretty-printing and parsing

As shown in the examples above, the internal representation (also called abstract syntax) of expressions quickly becomes hard to read and write as the expressions get larger. We need a printer and a parser to go back and forth between the abstract syntax and the concrete syntax, which in the case of expressions is the familiar algebraic notation (e.g. 2*x+1).

For the printing function, we take into account the usual precedence rules (i.e. * binds tighter than +) to avoid printing unnecessary parentheses. To this end, we maintain the current operator precedence and print parentheses around an operator only if its precedence is less than the current precedence.

#let print_expr exp =
   (* Local function definitions *)
   let open_paren prec op_prec =
     if prec > op_prec then print_string "(" in
   let close_paren prec op_prec =
     if prec > op_prec then print_string ")" in
   let rec print prec exp =     (* prec is the current precedence *)
     match exp with
       Const c -> print_float c
     | Var v -> print_string v
     | Sum(f, g) ->
         open_paren prec 0;
         print 0 f; print_string " + "; print 0 g;
         close_paren prec 0
     | Diff(f, g) ->
         open_paren prec 0;
         print 0 f; print_string " - "; print 1 g;
         close_paren prec 0
     | Prod(f, g) ->
         open_paren prec 2;
         print 2 f; print_string " * "; print 2 g;
         close_paren prec 2
     | Quot(f, g) ->
         open_paren prec 2;
         print 2 f; print_string " / "; print 3 g;
         close_paren prec 2
   in print 0 exp;;
val print_expr : expression -> unit = <fun>
 
#let e = Sum(Prod(Const 2.0, Var "x"), Const 1.0);;
val e : expression = Sum (Prod (Const 2., Var "x"), Const 1.)
 
#print_expr e; print_newline();;
2. * x + 1.
- : unit = ()
 
#print_expr (deriv e "x"); print_newline();;
2. * 1. + 0. * x + 0.
- : unit = ()

Parsing (transforming concrete syntax into abstract syntax) is usually more delicate. Caml offers several tools to help write parsers: on the one hand, Caml versions of the lexer generator Lex and the parser generator Yacc (see chapter 12), which handle LALR(1) languages using push-down automata; on the other hand, a predefined type of streams (of characters or tokens) and pattern-matching over streams, which facilitate the writing of recursive-descent parsers for LL(1) languages. An example using ocamllex and ocamlyacc is given in chapter 12. Here, we will use stream parsers. The syntactic support for stream parsers is provided by the Camlp4 preprocessor, which can be loaded into the interactive toplevel via the #load directive below.

##load "camlp4o.cma";;
	Camlp4 Parsing version 3.10.2+rc1

 
#open Genlex;;
 
 let lexer = make_lexer ["("; ")"; "+"; "-"; "*"; "/"];;
val lexer : char Stream.t -> Genlex.token Stream.t = <fun>

For the lexical analysis phase (transformation of the input text into a stream of tokens), we use a “generic” lexer provided in the standard library module Genlex. The make_lexer function takes a list of keywords and returns a lexing function that “tokenizes” an input stream of characters. Tokens are either identifiers, keywords, or literals (integer, floats, characters, strings). Whitespace and comments are skipped.

#let token_stream = lexer(Stream.of_string "1.0 +x");;
val token_stream : Genlex.token Stream.t = <abstr>
 
#Stream.next token_stream;;
- : Genlex.token = Float 1.
 
#Stream.next token_stream;;
- : Genlex.token = Kwd "+"
 
#Stream.next token_stream;;
- : Genlex.token = Ident "x"

The parser itself operates by pattern-matching on the stream of tokens. As usual with recursive descent parsers, we use several intermediate parsing functions to reflect the precedence and associativity of operators. Pattern-matching over streams is more powerful than on regular data structures, as it allows recursive calls to parsing functions inside the patterns, for matching sub-components of the input stream. See the Camlp4 documentation for more details.

#let rec parse_expr = parser
     [< e1 = parse_mult; e = parse_more_adds e1 >] -> e
 and parse_more_adds e1 = parser
     [< 'Kwd "+"; e2 = parse_mult; e = parse_more_adds (Sum(e1, e2)) >] -> e
   | [< 'Kwd "-"; e2 = parse_mult; e = parse_more_adds (Diff(e1, e2)) >] -> e
   | [< >] -> e1
 and parse_mult = parser
     [< e1 = parse_simple; e = parse_more_mults e1 >] -> e
 and parse_more_mults e1 = parser
     [< 'Kwd "*"; e2 = parse_simple; e = parse_more_mults (Prod(e1, e2)) >] -> e
   | [< 'Kwd "/"; e2 = parse_simple; e = parse_more_mults (Quot(e1, e2)) >] -> e
   | [< >] -> e1
 and parse_simple = parser
     [< 'Ident s >] -> Var s
   | [< 'Int i >] -> Const(float i)
   | [< 'Float f >] -> Const f
   | [< 'Kwd "("; e = parse_expr; 'Kwd ")" >] -> e;;
val parse_expr : Genlex.token Stream.t -> expression = <fun>
val parse_more_adds : expression -> Genlex.token Stream.t -> expression =
  <fun>
val parse_mult : Genlex.token Stream.t -> expression = <fun>
val parse_more_mults : expression -> Genlex.token Stream.t -> expression =
  <fun>
val parse_simple : Genlex.token Stream.t -> expression = <fun>
 
#let parse_expression = parser [< e = parse_expr; _ = Stream.empty >] -> e;;
val parse_expression : Genlex.token Stream.t -> expression = <fun>

Composing the lexer and parser, we finally obtain a function to read an expression from a character string:

#let read_expression s = parse_expression(lexer(Stream.of_string s));;
val read_expression : string -> expression = <fun>
 
#read_expression "2*(x+y)";;
- : expression = Prod (Const 2., Sum (Var "x", Var "y"))

A small puzzle: why do we get different results in the following two examples?

#read_expression "x - 1";;
- : expression = Diff (Var "x", Const 1.)
 
#read_expression "x-1";;
Exception: Stream.Error "".

Answer: the generic lexer provided by Genlex recognizes negative integer literals as one integer token. Hence, x-1 is read as the token Ident "x" followed by the token Int(-1); this sequence does not match any of the parser rules. On the other hand, the second space in x - 1 causes the lexer to return the three expected tokens: Ident "x", then Kwd "-", then Int(1).

1.9  Standalone Caml programs

All examples given so far were executed under the interactive system. Caml code can also be compiled separately and executed non-interactively using the batch compilers ocamlc or ocamlopt. The source code must be put in a file with extension .ml. It consists of a sequence of phrases, which will be evaluated at runtime in their order of appearance in the source file. Unlike in interactive mode, types and values are not printed automatically; the program must call printing functions explicitly to produce some output. Here is a sample standalone program to print Fibonacci numbers:

(* File fib.ml *)
let rec fib n =
  if n < 2 then 1 else fib(n-1) + fib(n-2);;
let main () =
  let arg = int_of_string Sys.argv.(1) in
  print_int(fib arg);
  print_newline();
  exit 0;;
main ();;

Sys.argv is an array of strings containing the command-line parameters. Sys.argv.(1) is thus the first command-line parameter. The program above is compiled and executed with the following shell commands:

$ ocamlc -o fib fib.ml
$ ./fib 10
89
$ ./fib 20
10946

Chapter 2  The module system

This chapter introduces the module system of Objective Caml.

2.1  Structures

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 structure and is introduced by the structend construct, which contains an arbitrary sequence of definitions. The structure is usually given a name with the module binding. Here is for instance a structure packaging together a type of priority queues and their operations:

#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;;
module PrioQueue :
  sig
    type priority = int
    type '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

Outside the structure, its components can be referred to using the “dot notation”, that is, identifiers qualified by a structure name. For instance, PrioQueue.insert in a value context is the function insert defined inside the structure PrioQueue. Similarly, PrioQueue.queue in a type context is the type queue defined in PrioQueue.

#PrioQueue.insert PrioQueue.empty 1 "hello";;
- : string PrioQueue.queue =
PrioQueue.Node (1, "hello", PrioQueue.Empty, PrioQueue.Empty)

2.2  Signatures

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 empty, insert and extract, but not the auxiliary function remove_top. Similarly, it makes the queue type abstract (by not providing its actual representation as a concrete type).

#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;;
module type PRIOQUEUE =
  sig
    type priority = int
    type '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

Restricting the PrioQueue structure by this signature results in another view of the PrioQueue structure where the remove_top function is not accessible and the actual representation of priority queues is hidden:

#module AbstractPrioQueue = (PrioQueue : PRIOQUEUE);;
module AbstractPrioQueue : PRIOQUEUE
 
#AbstractPrioQueue.remove_top;;
Unbound value AbstractPrioQueue.remove_top
 
#AbstractPrioQueue.insert AbstractPrioQueue.empty 1 "hello";;
- : string AbstractPrioQueue.queue = <abstr>

The restriction can also be performed during the definition of the structure, as in

module PrioQueue = (struct ... end : PRIOQUEUE);;

An alternate syntax is provided for the above:

module PrioQueue : PRIOQUEUE = struct ... end;;

2.3  Functors

Functors are “functions” from structures to structures. They are used to express parameterized structures: a structure A parameterized by a structure B is simply a functor F with a formal parameter B (along with the expected signature for B) which returns the actual structure A itself. The functor F can then be applied to one or several implementations B1Bn of B, yielding the corresponding structures A1An.

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):

#type comparison = Less | Equal | Greater;;
type comparison = Less | Equal | Greater
 
#module type ORDERED_TYPE =
   sig
     type t
     val compare: t -> t -> comparison
   end;;
module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end
 
#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;;
module Set :
  functor (Elt : ORDERED_TYPE) ->
    sig
      type element = Elt.t
      type 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

By applying the Set functor to a structure implementing an ordered type, we obtain set operations for this type:

#module OrderedString =
   struct
     type t = string
     let compare x y = if x = y then Equal else if x < y then Less else Greater
   end;;
module OrderedString :
  sig type t = string val compare : 'a -> 'a -> comparison end
 
#module StringSet = Set(OrderedString);;
module StringSet :
  sig
    type element = OrderedString.t
    type 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
 
#StringSet.member "bar" (StringSet.add "foo" StringSet.empty);;
- : bool = false

2.4  Functors and type abstraction

As in the PrioQueue example, it would be good style to hide the actual implementation of the type set, 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 Set by a suitable functor signature:

#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;;
module type SETFUNCTOR =
  functor (Elt : ORDERED_TYPE) ->
    sig
      type element = Elt.t
      type set
      val empty : set
      val add : element -> set -> set
      val member : element -> set -> bool
    end
 
#module AbstractSet = (Set : SETFUNCTOR);;
module AbstractSet : SETFUNCTOR
 
#module AbstractStringSet = AbstractSet(OrderedString);;
module AbstractStringSet :
  sig
    type element = OrderedString.t
    type set = AbstractSet(OrderedString).set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
  end
 
#AbstractStringSet.add "gee" AbstractStringSet.empty;;
- : AbstractStringSet.set = <abstr>

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:

#module type SET =
   sig
     type element
     type set
     val empty : set
     val add : element -> set -> set
     val member : element -> set -> bool
   end;;
module type SET =
  sig
    type element
    type set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
  end
 
#module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);;
module WrongSet : functor (Elt : ORDERED_TYPE) -> SET
 
#module WrongStringSet = WrongSet(OrderedString);;
module WrongStringSet :
  sig
    type element = WrongSet(OrderedString).element
    type set = WrongSet(OrderedString).set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
  end
 
#WrongStringSet.add "gee" WrongStringSet.empty;;
This expression has type string but is here used with type
  WrongStringSet.element = WrongSet(OrderedString).element

The problem here is that SET specifies the type element abstractly, so that the type equality between element in the result of the functor and t in its argument is forgotten. Consequently, WrongStringSet.element is not the same type as string, and the operations of WrongStringSet cannot be applied to strings. As demonstrated above, it is important that the type element in the signature SET be declared equal to Elt.t; unfortunately, this is impossible above since SET is defined in a context where Elt does not exist. To overcome this difficulty, Objective Caml provides a with type construct over signatures that allows to enrich a signature with extra type equalities:

#module AbstractSet = 
   (Set : functor(Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));;
module AbstractSet :
  functor (Elt : ORDERED_TYPE) ->
    sig
      type element = Elt.t
      type set
      val empty : set
      val add : element -> set -> set
      val member : element -> set -> bool
    end

As in the case of simple structures, an alternate syntax is provided for defining functors and restricting their result:

module AbstractSet(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) =
  struct ... end;;

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 OrderedString structure. For instance, we compare strings without distinguishing upper and lower case.

#module NoCaseString =
   struct
     type t = string
     let compare s1 s2 =
       OrderedString.compare (String.lowercase s1) (String.lowercase s2)
   end;;
module NoCaseString :
  sig type t = string val compare : string -> string -> comparison end
 
#module NoCaseStringSet = AbstractSet(NoCaseString);;
module NoCaseStringSet :
  sig
    type element = NoCaseString.t
    type set = AbstractSet(NoCaseString).set
    val empty : set
    val add : element -> set -> set
    val member : element -> set -> bool
  end
 
#NoCaseStringSet.add "FOO" AbstractStringSet.empty;;
This expression has type
  AbstractStringSet.set = AbstractSet(OrderedString).set
but is here used with type
  NoCaseStringSet.set = AbstractSet(NoCaseString).set

Notice that the two types AbstractStringSet.set and NoCaseStringSet.set 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 AbstractStringSet to values of type NoCaseStringSet.set could give incorrect results, or build lists that violate the invariants of NoCaseStringSet.

2.5  Modules and separate compilation

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.

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 A comprises two files:

Both files define a structure named A as if the following definition was entered at top-level:

module A: sig (* contents of file A.mli *) end
        = struct (* contents of file A.ml *) end;;

The files defining the compilation units can be compiled separately using the ocamlc -c command (the -c option means “compile only, do not try to link”); this produces compiled interface files (with extension .cmi) and compiled object code files (with extension .cmo). When all units have been compiled, their .cmo files are linked together using the ocaml command. For instance, the following commands compile and link a program composed of two compilation units Aux and Main:

$ 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

The program behaves exactly as if the following phrases were entered at top-level:

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

In particular, Main can refer to Aux: the definitions and declarations contained in Main.ml and Main.mli can refer to definition in Aux.ml, using the Aux.ident notation, provided these definitions are exported in Aux.mli.

The order in which the .cmo files are given to ocaml during the linking phase determines the order in which the module definitions occur. Hence, in the example above, Aux appears first and Main can refer to it, but Aux cannot refer to Main.

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.

Chapter 3  Objects in Caml

(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)



This chapter gives an overview of the object-oriented features of Objective Caml. Note that the relation between object, class and type in Objective Caml is very different from that in main stream object-oriented languages like Java or C++, so that you should not assume that similar keywords mean the same thing.

3.1 Classes and objects
3.2 Immediate objects
3.3 Reference to self
3.4 Initializers
3.5 Virtual methods
3.6 Private methods
3.7 Class interfaces
3.8 Inheritance
3.9 Multiple inheritance
3.10 Parameterized classes
3.11 Polymorphic methods
3.12 Using coercions
3.13 Functional objects
3.14 Cloning objects
3.15 Recursive classes
3.16 Binary methods
3.17 Friends

3.1  Classes and objects

The class point below defines one instance variable x and two methods get_x and move. The initial value of the instance variable is 0. The variable x is declared mutable, so the method move can change its value.

#class point =
   object 
     val mutable x = 0
     method get_x = x
     method move d = x <- x + d
   end;;
class point :
  object val mutable x : int method get_x : int method move : int -> unit end

We now create a new point p, instance of the point class.

#let p = new point;;
val p : point = <obj>

Note that the type of p is point. This is an abbreviation automatically defined by the class definition above. It stands for the object type <get_x : int; move : int -> unit>, listing the methods of class point along with their types.

We now invoke some methods to p:

#p#get_x;;
- : int = 0
 
#p#move 3;;
- : unit = ()
 
#p#get_x;;
- : int = 3

The evaluation of the body of a class only takes place at object creation time. Therefore, in the following example, the instance variable x is initialized to different values for two different objects.

#let x0 = ref 0;;
val x0 : int ref = {contents = 0}
 
#class point =
   object 
     val mutable x = incr x0; !x0
     method get_x = x
     method move d = x <- x + d
   end;;
class point :
  object val mutable x : int method get_x : int method move : int -> unit end
 
#new point#get_x;;
- : int = 1
 
#new point#get_x;;
- : int = 2

The class point can also be abstracted over the initial values of the x coordinate.

#class point = fun x_init -> 
   object 
     val mutable x = x_init
     method get_x = x
     method move d = x <- x + d
   end;;
class point :
  int ->
  object val mutable x : int method get_x : int method move : int -> unit end

Like in function definitions, the definition above can be abbreviated as:

#class point x_init =
   object 
     val mutable x = x_init
     method get_x = x
     method move d = x <- x + d
   end;;
class point :
  int ->
  object val mutable x : int method get_x : int method move : int -> unit end

An instance of the class point is now a function that expects an initial parameter to create a point object:

#new point;;
- : int -> point = <fun>
 
#let p = new point 7;;
val p : point = <obj>

The parameter x_init is, of course, visible in the whole body of the definition, including methods. For instance, the method get_offset in the class below returns the position of the object relative to its initial position.

#class point x_init =
   object 
     val mutable x = x_init
     method get_x = x
     method get_offset = x - x_init
     method move d = x <- x + d 
   end;;
class point :
  int ->
  object
    val mutable x : int
    method get_offset : int
    method get_x : int
    method move : int -> unit
  end

Expressions can be evaluated and bound before defining the object body of the class. This is useful to enforce invariants. For instance, points can be automatically adjusted to the nearest point on a grid, as follows:

#class adjusted_point x_init =
   let origin = (x_init / 10) * 10 in
   object 
     val mutable x = origin
     method get_x = x
     method get_offset = x - origin
     method move d = x <- x + d
   end;;
class adjusted_point :
  int ->
  object
    val mutable x : int
    method get_offset : int
    method get_x : int
    method move : int -> unit
  end

(One could also raise an exception if the x_init coordinate is not on the grid.) In fact, the same effect could here be obtained by calling the definition of class point with the value of the origin.

#class adjusted_point x_init =  point ((x_init / 10) * 10);;
class adjusted_point : int -> point

An alternative solution would have been to define the adjustment in a special allocation function:

#let new_adjusted_point x_init = new point ((x_init / 10) * 10);;
val new_adjusted_point : int -> point = <fun>

However, the former pattern is generally more appropriate, since the code for adjustment is part of the definition of the class and will be inherited.

This ability provides class constructors as can be found in other languages. Several constructors can be defined this way to build objects of the same class but with different initialization patterns; an alternative is to use initializers, as decribed below in section 3.4.

3.2  Immediate objects

There is another, more direct way to create an object: create it without going through a class.

The syntax is exactly the same as for class expressions, but the result is a single object rather than a class. All the constructs described in the rest of this section also apply to immediate objects.

#let p =
   object 
     val mutable x = 0
     method get_x = x
     method move d = x <- x + d
   end;;
val p : < get_x : int; move : int -> unit > = <obj>
 
#p#get_x;;
- : int = 0
 
#p#move 3;;
- : unit = ()
 
#p#get_x;;
- : int = 3

Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment.

#let minmax x y =
   if x < y then object method min = x method max = y end
   else object method min = y method max = x end;;
val minmax : 'a -> 'a -> < max : 'a; min : 'a > = <fun>

Immediate objects have two weaknesses compared to classes: their types are not abbreviated, and you cannot inherit from them. But these two weaknesses can be advantages in some situations, as we will see in sections 3.3 and 3.10.

3.3  Reference to self

A method or an initializer can send messages to self (that is, the current object). For that, self must be explicitly bound, here to the variable s (s could be any identifier, even though we will often choose the name self.)

#class printable_point x_init =
   object (s)
     val mutable x = x_init
     method get_x = x
     method move d = x <- x + d
     method print = print_int s#get_x
   end;;
class printable_point :
  int ->
  object
    val mutable x : int
    method get_x : int
    method move : int -> unit
    method print : unit
  end
 
#let p = new printable_point 7;;
val p : printable_point = <obj>
 
#p#print;;
7- : unit = ()

Dynamically, the variable s is bound at the invocation of a method. In particular, when the class printable_point is inherited, the variable s will be correctly bound to the object of the subclass.

A common problem with self is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example.

#let ints = ref [];;
val ints : '_a list ref = {contents = []}
 
#class my_int =
   object (self)
     method n = 1
     method register = ints := self :: !ints
   end;;
This expression has type < n : int; register : 'a; .. >
but is here used with type 'b
Self type cannot escape its class

You can ignore the first two lines of the error message. What matters is the last one: putting self into an external reference would make it impossible to extend it afterwards. We will see in section 3.12 a workaround to this problem. Note however that, since immediate objects are not extensible, the problem does not occur with them.

#let my_int =
   object (self)
     method n = 1
     method register = ints := self :: !ints
   end;;
val my_int : < n : int; register : unit > = <obj>

3.4  Initializers

Let-bindings within class definitions are evaluated before the object is constructed. It is also possible to evaluate an expression immediately after the object has been built. Such code is written as an anonymous hidden method called an initializer. Therefore, is can access self and the instance variables.

#class printable_point x_init =
   let origin = (x_init / 10) * 10 in
   object (self)
     val mutable x = origin
     method get_x = x
     method move d = x <- x + d
     method print = print_int self#get_x
     initializer print_string "new point at "; self#print; print_newline()
   end;;
class printable_point :
  int ->
  object
    val mutable x : int
    method get_x : int
    method move : int -> unit
    method print : unit
  end
 
#let p = new printable_point 17;;
new point at 10
val p : printable_point = <obj>

Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section 5.1.

3.5  Virtual methods

It is possible to declare a method without actually defining it, using the keyword virtual. This method will be provided later in subclasses. A class containing virtual methods must be flagged virtual, and cannot be instantiated (that is, no object of this class can be created). It still defines type abbreviations (treating virtual methods as other methods.)

#class virtual abstract_point x_init =
   object (self)
     method virtual get_x : int
     method get_offset = self#get_x - x_init
     method virtual move : int -> unit
   end;;
class virtual abstract_point :
  int ->
  object
    method get_offset : int
    method virtual get_x : int
    method virtual move : int -> unit
  end
 
#class point x_init =
   object
     inherit abstract_point x_init
     val mutable x = x_init
     method get_x = x
     method move d = x <- x + d 
   end;;
class point :
  int ->
  object
    val mutable x : int
    method get_offset : int
    method get_x : int
    method move : int -> unit
  end

Instance variables can also be declared as virtual, with the same effect as with methods.

#class virtual abstract_point2 =
   object
     val mutable virtual x : int
     method move d = x <- x + d 
   end;;
class virtual abstract_point2 :
  object val mutable virtual x : int method move : int -> unit end
 
#class point2 x_init =
   object
     inherit abstract_point2
     val mutable x = x_init
     method get_offset = x - x_init
   end;;
class point2 :
  int ->
  object
    val mutable x : int
    method get_offset : int
    method move : int -> unit
  end

3.6  Private methods

Private methods are methods that do not appear in object interfaces. They can only be invoked from other methods of the same object.

#class restricted_point x_init =
   object (self)
     val mutable x = x_init
     method get_x = x
     method private move d = x <- x + d
     method bump = self#move 1
   end;;
class restricted_point :
  int ->
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method private move : int -> unit
  end
 
#let p = new restricted_point 0;;
val p : restricted_point = <obj>
 
#p#move 10;;
This expression has type restricted_point
It has no method move
 
#p#bump;;
- : unit = ()

Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in Objective Caml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section 3.17.

Private methods are inherited (they are by default visible in subclasses), unless they are hidden by signature matching, as described below.

Private methods can be made public in a subclass.

#class point_again x =
   object (self)
     inherit restricted_point x
     method virtual move : _
   end;;
class point_again :
  int ->
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method move : int -> unit
  end

The annotation virtual here is only used to mention a method without providing its definition. Since we didn't add the private annotation, this makes the method public, keeping the original definition.

An alternative definition is

#class point_again x =
   object (self : < move : _; ..> )
     inherit restricted_point x
   end;;
class point_again :
  int ->
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method move : int -> unit
  end

The constraint on self's type is requiring a public move method, and this is sufficient to override private.

One could think that a private method should remain private in a subclass. However, since the method is visible in a subclass, it is always possible to pick its code and define a method of the same name that runs that code, so yet another (heavier) solution would be:

#class point_again x =
   object
     inherit restricted_point x as super
     method move = super#move 
   end;;
class point_again :
  int ->
  object
    val mutable x : int
    method bump : unit
    method get_x : int
    method move : int -> unit
  end

Of course, private methods can also be virtual. Then, the keywords must appear in this order method private virtual.

3.7  Class interfaces

Class interfaces are inferred from class definitions. They may also be defined directly and used to restrict the type of a class. Like class declarations, they also define a new type abbreviation.

#class type restricted_point_type = 
   object
     method get_x : int
     method bump : unit
 end;;
class type restricted_point_type =
  object method bump : unit method get_x : int end
 
#fun (x : restricted_point_type) -> x;;
- : restricted_point_type -> restricted_point_type = <fun>

In addition to program documentation, class interfaces can be used to constrain the type of a class. Both concrete instance variables and concrete private methods can be hidden by a class type constraint. Public methods and virtual members, however, cannot.

#class restricted_point' x = (restricted_point x : restricted_point_type);;
class restricted_point' : int -> restricted_point_type

Or, equivalently:

#class restricted_point' = (restricted_point : int -> restricted_point_type);;
class restricted_point' : int -> restricted_point_type

The interface of a class can also be specified in a module signature, and used to restrict the inferred signature of a module.

#module type POINT = sig 
   class restricted_point' : int ->
     object    
       method get_x : int
       method bump : unit
     end 
 end;;
module type POINT =
  sig
    class restricted_point' :
      int -> object method bump : unit method get_x : int end
  end
 
#module Point : POINT = struct 
   class restricted_point' = restricted_point
 end;;
module Point : POINT

3.8  Inheritance

We illustrate inheritance by defining a class of colored points that inherits from the class of points. This class has all instance variables and all methods of class point, plus a new instance variable c and a new method color.

#class colored_point x (c : string) =
   object 
     inherit point x
     val c = c
     method color = c
   end;;
class colored_point :
  int ->
  string ->
  object
    val c : string
    val mutable x : int
    method color : string
    method get_offset : int
    method get_x : int
    method move : int -> unit
  end
 
#let p' = new colored_point 5 "red";;
val p' : colored_point = <obj>
 
#p'#get_x, p'#color;;
- : int * string = (5, "red")

A point and a colored point have incompatible types, since a point has no method color. However, the function get_x below is a generic function applying method get_x to any object p that has this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it applies to both points and colored points.

#let get_succ_x p = p#get_x + 1;;
val get_succ_x : < get_x : int; .. > -> int = <fun>
 
#get_succ_x p + get_succ_x p';;
- : int = 8

Methods need not be declared previously, as shown by the example:

#let set_x p = p#set_x;;
val set_x : < set_x : 'a; .. > -> 'a = <fun>
 
#let incr p = set_x p (get_succ_x p);;
val incr : < get_x : int; set_x : int -> 'a; .. > -> 'a = <fun>

3.9  Multiple inheritance

Multiple inheritance is allowed. Only the last definition of a method is kept: the redefinition in a subclass of a method that was visible in the parent class overrides the definition in the parent class. Previous definitions of a method can be reused by binding the related ancestor. Below, super is bound to the ancestor printable_point. The name super is a pseudo value identifier that can only be used to invoke a super-class method, as in super#print.

#class printable_colored_point y c = 
   object (self)
     val c = c
     method color = c
     inherit printable_point y as super
     method print =
       print_string "(";
       super#print;
       print_string ", ";
       print_string (self#color);
       print_string ")"
   end;;
class printable_colored_point :
  int ->
  string ->
  object
    val c : string
    val mutable x : int
    method color : string
    method get_x : int
    method move : int -> unit
    method print : unit
  end
 
#let p' = new printable_colored_point 17 "red";;
new point at (10, red)
val p' : printable_colored_point = <obj>
 
#p'#print;;
(10, red)- : unit = ()

A private method that has been hidden in the parent class is no longer visible, and is thus not overridden. Since initializers are treated as private methods, all initializers along the class hierarchy are evaluated, in the order they are introduced.

3.10  Parameterized classes

Reference cells can be implemented as objects. The naive definition fails to typecheck:

#class ref x_init =
   object 
     val mutable x = x_init
     method get = x
     method set y = x <- y
   end;;
Some type variables are unbound in this type:
  class ref :
    'a ->
    object val mutable x : 'a method get : 'a method set : 'a -> unit end
The method get has type 'a where 'a is unbound

The reason is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus either the class should be parametric, or the method type should be constrained to a monomorphic type. A monomorphic instance of the class could be defined by:

#class ref (x_init:int) =
   object 
     val mutable x = x_init
     method get = x
     method set y = x <- y
   end;;
class ref :
  int ->
  object val mutable x : int method get : int method set : int -> unit end

Note that since immediate objects do not define a class type, the have no such restriction.

#let new_ref x_init =
   object 
     val mutable x = x_init
     method get = x
     method set y = x <- y
   end;;
val new_ref : 'a -> < get : 'a; set : 'a -> unit > = <fun>

On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are always listed between [ and ]. The type parameters must also be bound somewhere in the class body by a type constraint.

#class ['a] ref x_init = 
   object 
     val mutable x = (x_init : 'a)
     method get = x
     method set y = x <- y
   end;;
class ['a] ref :
  'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
 
#let r = new ref 1 in r#set 2; (r#get);;
- : int = 2

The type parameter in the declaration may actually be constrained in the body of the class definition. In the class type, the actual value of the type parameter is displayed in the constraint clause.

#class ['a] ref_succ (x_init:'a) = 
   object
     val mutable x = x_init + 1
     method get = x
     method set y = x <- y
   end;;
class ['a] ref_succ :
  'a ->
  object
    constraint 'a = int
    val mutable x : int
    method get : int
    method set : int -> unit
  end

Let us consider a more complex example: define a circle, whose center may be any kind of point. We put an additional type constraint in method move, since no free variables must remain unaccounted for by the class type parameters.

#class ['a] circle (c : 'a) =
   object 
     val mutable center = c
     method center = center
     method set_center c = center <- c
     method move = (center#move : int -> unit)
   end;;
class ['a] circle :
  'a ->
  object
    constraint 'a = < move : int -> unit; .. >
    val mutable center : 'a
    method center : 'a
    method move : int -> unit
    method set_center : 'a -> unit
  end

An alternate definition of circle, using a constraint clause in the class definition, is shown below. The type #point used below in the constraint clause is an abbreviation produced by the definition of class point. This abbreviation unifies with the type of any object belonging to a subclass of class point. It actually expands to < get_x : int; move : int -> unit; .. >. This leads to the following alternate definition of circle, which has slightly stronger constraints on its argument, as we now expect center to have a method get_x.

#class ['a] circle (c : 'a) =
   object 
     constraint 'a = #point
     val mutable center = c
     method center = center
     method set_center c = center <- c
     method move = center#move
   end;;
class ['a] circle :
  'a ->
  object
    constraint 'a = #point
    val mutable center : 'a
    method center : 'a
    method move : int -> unit
    method set_center : 'a -> unit
  end

The class colored_circle is a specialized version of class circle that requires the type of the center to unify with #colored_point, and adds a method color. Note that when specializing a parameterized class, the instance of type parameter must always be explicitly given. It is again written between [ and ].

#class ['a] colored_circle c =
   object
     constraint 'a = #colored_point
     inherit ['a] circle c
     method color = center#color
   end;;
class ['a] colored_circle :
  'a ->
  object
    constraint 'a = #colored_point
    val mutable center : 'a
    method center : 'a
    method color : string
    method move : int -> unit
    method set_center : 'a -> unit
  end

3.11  Polymorphic methods

While parameterized classes may be polymorphic in their contents, they are not enough to allow polymorphism of method use.

A classical example is defining an iterator.

#List.fold_left;;
- : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a = <fun>
 
#class ['a] intlist (l : int list) =
   object
     method empty = (l = [])
     method fold f (accu : 'a) = List.fold_left f accu l
   end;;
class ['a] intlist :
  int list ->
  object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end

At first look, we seem to have a polymorphic iterator, however this does not work in practice.

#let l = new intlist [1; 2; 3];;
val l : '_a intlist = <obj>
 
#l#fold (fun x y -> x+y) 0;;
- : int = 6
 
#l;;
- : int intlist = <obj>
 
#l#fold (fun s x -> s ^ string_of_int x ^ " ") "";;
This expression has type int but is here used with type string

Our iterator works, as shows its first use for summation. However, since objects themselves are not polymorphic (only their constructors are), using the fold method fixes its type for this individual object. Our next attempt to use it as a string iterator fails.

The problem here is that quantification was wrongly located: this is not the class we want to be polymorphic, but the fold method. This can be achieved by giving an explicitly polymorphic type in the method definition.

#class intlist (l : int list) =
   object
     method empty = (l = [])
     method fold : 'a. ('a -> int -> 'a) -> 'a -> 'a =
       fun f accu -> List.fold_left f accu l
   end;;
class intlist :
  int list ->
  object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end
 
#let l = new intlist [1; 2; 3];;
val l : intlist = <obj>
 
#l#fold (fun x y -> x+y) 0;;
- : int = 6
 
#l#fold (fun s x -> s ^ string_of_int x ^ " ") "";;
- : string = "1 2 3 "

As you can see in the class type shown by the compiler, while polymorphic method types must be fully explicit in class definitions (appearing immediately after the method name), quantified type variables can be left implicit in class descriptions. Why require types to be explicit? The problem is that (int -> int -> int) -> int -> int would also be a valid type for fold, and it happens to be incompatible with the polymorphic type we gave (automatic instantiation only works for toplevel types variables, not for inner quantifiers, where it becomes an undecidable problem.) So the compiler cannot choose between those two types, and must be helped.

However, the type can be completely omitted in the class definition if it is already known, through inheritance or type constraints on self. Here is an example of method overriding.

#class intlist_rev l =
   object
     inherit intlist l
     method fold f accu = List.fold_left f accu (List.rev l)
   end;;

The following idiom separates description and definition.

#class type ['a] iterator =
   object method fold : ('b -> 'a -> 'b) -> 'b -> 'b end;;
 
 class intlist l =
   object (self : int #iterator)
     method empty = (l = [])
     method fold f accu = List.fold_left f accu l
   end;;

Note here the (self : int #iterator) idiom, which ensures that this object implements the interface iterator.

Polymorphic methods are called in exactly the same way as normal methods, but you should be aware of some limitations of type inference. Namely, a polymorphic method can only be called if its type is known at the call site. Otherwise, the method will be assumed to be monomorphic, and given an incompatible type.

#let sum lst = lst#fold (fun x y -> x+y) 0;;
val sum : < fold : (int -> int -> int) -> int -> 'a; .. > -> 'a = <fun>
 
#sum l;;
This expression has type intlist but is here used with type
  < fold : (int -> int -> int) -> int -> 'a; .. >
Types for method fold are incompatible

The workaround is easy: you should put a type constraint on the parameter.

#let sum (lst : _ #iterator) = lst#fold (fun x y -> x+y) 0;;
val sum : int #iterator -> int = <fun>

Of course the constraint may also be an explicit method type. Only occurences of quantified variables are required.

#let sum lst =
   (lst : < fold : 'a. ('a -> _ -> 'a) -> 'a -> 'a; .. >)#fold (+) 0;;
val sum : < fold : 'a. ('a -> int -> 'a) -> 'a -> 'a; .. > -> int = <fun>

Another use of polymorphic methods is to allow some form of implicit subtyping in method arguments. We have already seen in section 3.8 how some functions may be polymorphic in the class of their argument. This can be extended to methods.

#class type point0 = object method get_x : int end;;
class type point0 = object method get_x : int end
 
#class distance_point x =
   object
     inherit point x
     method distance : 'a. (#point0 as 'a) -> int =
       fun other -> abs (other#get_x - x)
   end;;
class distance_point :
  int ->
  object
    val mutable x : int
    method distance : #point0 -> int
    method get_offset : int
    method get_x : int
    method move : int -> unit
  end
 
#let p = new distance_point 3 in
 (p#distance (new point 8), p#distance (new colored_point 1 "blue"));;
- : int * int = (5, 2)

Note here the special syntax (#point0 as 'a) we have to use to quantify the extensible part of #point0. As for the variable binder, it can be omitted in class specifications. If you want polymorphism inside object field it must be quantified independently.

#class multi_poly =
   object
     method m1 : 'a. (< n1 : 'b. 'b -> 'b; .. > as 'a) -> _ =
       fun o -> o#n1 true, o#n1 "hello"
     method m2 : 'a 'b. (< n2 : 'b -> bool; .. > as 'a) -> 'b -> _ =
       fun o x -> o#n2 x
   end;;
class multi_poly :
  object
    method m1 : < n1 : 'a. 'a -> 'a; .. > -> bool * string
    method m2 : < n2 : 'b -> bool; .. > -> 'b -> bool
  end

In method m1, o must be an object with at least a method n1, itself polymorphic. In method m2, the argument of n2 and x must have the same type, which is quantified at the same level as 'a.

3.12  Using coercions

Subtyping is never implicit. There are, however, two ways to perform subtyping. The most general construction is fully explicit: both the domain and the codomain of the type coercion must be given.

We have seen that points and colored points have incompatible types. For instance, they cannot be mixed in the same list. However, a colored point can be coerced to a point, hiding its color method:

#let colored_point_to_point cp = (cp : colored_point :> point);;
val colored_point_to_point : colored_point -> point = <fun>
 
#let p = new point 3 and q = new colored_point 4 "blue";;
val p : point = <obj>
val q : colored_point = <obj>
 
#let l = [p; (colored_point_to_point q)];;
val l : point list = [<obj>; <obj>]

An object of type t can be seen as an object of type t' only if t is a subtype of t'. For instance, a point cannot be seen as a colored point.

#(p : point :> colored_point);;
Type point = < get_offset : int; get_x : int; move : int -> unit >
is not a subtype of type
  colored_point =
    < color : string; get_offset : int; get_x : int; move : int -> unit > 

Indeed, narrowing coercions without runtime checks would be unsafe. Runtime type checks might raise exceptions, and they would require the presence of type information at runtime, which is not the case in the Objective Caml system. For these reasons, there is no such operation available in the language.

Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types. For instance, the class of colored points could have been defined directly, without inheriting from the class of points; the type of colored points would remain unchanged and thus still be a subtype of points.

The domain of a coercion can often be omitted. For instance, one can define:

#let to_point cp = (cp :> point);;
val to_point : #point -> point = <fun>

In this case, the function colored_point_to_point is an instance of the function to_point. This is not always true, however. The fully explicit coercion is more precise and is sometimes unavoidable. Consider, for example, the following class:

#class c0 = object method m = {< >} method n = 0 end;;
class c0 : object ('a) method m : 'a method n : int end

The object type c0 is an abbreviation for <m : 'a; n : int> as 'a. Consider now the type declaration:

#class type c1 =  object method m : c1 end;;
class type c1 = object method m : c1 end

The object type c1 is an abbreviation for the type <m : 'a> as 'a. The coercion from an object of type c0 to an object of type c1 is correct:

#fun (x:c0) -> (x : c0 :> c1);;
- : c0 -> c1 = <fun>

However, the domain of the coercion cannot be omitted here:

#fun (x:c0) -> (x :> c1);;
This expression cannot be coerced to type c1 = < m : c1 >; it has type
  c0 = < m : c0; n : int >
but is here used with type < m : #c1 as 'a; .. >
Type c0 = < m : c0; n : int > is not compatible with type 'a = < m : c1; .. > 
Type c0 = < m : c0; n : int > is not compatible with type c1 = < m : c1 > 
The second object type has no method n.
This simple coercion was not fully general. Consider using a double coercion.

The solution is to use the explicit form. Sometimes, a change in the class-type definition can also solve the problem

#class type c2 =  object ('a) method m : 'a end;;
class type c2 = object ('a) method m : 'a end
 
#fun (x:c0) -> (x :> c2);;
- : c0 -> c2 = <fun>

While class types c1 and c2 are different, both object types c1 and c2 expand to the same object type (same method names and types). Yet, when the domain of a coercion is left implicit and its co-domain is an abbreviation of a known class type, then the class type, rather than the object type, is used to derive the coercion function. This allows to leave the domain implicit in most cases when coercing form a subclass to its superclass. The type of a coercion can always be seen as below:

#let to_c1 x = (x :> c1);;
val to_c1 : < m : #c1; .. > -> c1 = <fun>
 
#let to_c2 x = (x :> c2);;
val to_c2 : #c2 -> c2 = <fun>

Note the difference between the two coercions: in the second case, the type #c2 = < m : 'a; .. > as 'a is polymorphically recursive (according to the explicit recursion in the class type of c2); hence the success of applying this coercion to an object of class c0. On the other hand, in the first case, c1 was only expanded and unrolled twice to obtain < m : < m : c1; .. >; .. > (remember #c1 = < m : c1; .. >), without introducing recursion. You may also note that the type of to_c2 is #c2 -> c2 while the type of to_c1 is more general than #c1 -> c1. This is not always true, since there are class types for which some instances of #c are not subtypes of c, as explained in section 3.16. Yet, for parameterless classes the coercion (_ :> c) is always more general than (_ : #c :> c).

A common problem may occur when one tries to define a coercion to a class c while defining class c. The problem is due to the type abbreviation not being completely defined yet, and so its subtypes are not clearly known. Then, a coercion (_ :> c) or (_ : #c :> c) is taken to be the identity function, as in

#function x -> (x :> 'a);;
- : 'a -> 'a = <fun>

As a consequence, if the coercion is applied to self, as in the following example, the type of self is unified with the closed type c (a closed object type is an object type without ellipsis). This would constrain the type of self be closed and is thus rejected. Indeed, the type of self cannot be closed: this would prevent any further extension of the class. Therefore, a type error is generated when the unification of this type with another type would result in a closed object type.

#class c = object method m = 1 end
 and d = object (self)
   inherit c
   method n = 2
   method as_c = (self :> c)
 end;;
This expression cannot be coerced to type c = < m : int >; it has type
  < as_c : c; m : int; n : int; .. >
but is here used with type c
Self type cannot be unified with a closed object type

However, the most common instance of this problem, coercing self to its current class, is detected as a special case by the type checker, and properly typed.

#class c = object (self) method m = (self :> c) end;;
class c : object method m : c end

This allows the following idiom, keeping a list of all objects belonging to a class or its subclasses:

#let all_c = ref [];;
val all_c : '_a list ref = {contents = []}
 
#class c (m : int) =
   object (self)
     method m = m
     initializer all_c := (self :> c) :: !all_c
   end;;
class c : int -> object method m : int end

This idiom can in turn be used to retrieve an object whose type has been weakened:

#let rec lookup_obj obj = function [] -> raise Not_found
   | obj' :: l ->
      if (obj :> < >) = (obj' :> < >) then obj' else lookup_obj obj l ;;
val lookup_obj : < .. > -> (< .. > as 'a) list -> 'a = <fun>
 
#let lookup_c obj = lookup_obj obj !all_c;;
val lookup_c : < .. > -> < m : int > = <fun>

The type < m : int > we see here is just the expansion of c, due to the use of a reference; we have succeeded in getting back an object of type c.


The previous coercion problem can often be avoided by first defining the abbreviation, using a class type:

#class type c' = object method m : int end;;
class type c' = object method m : int end
 
#class c : c' = object method m = 1 end
 and d = object (self)
   inherit c
   method n = 2
   method as_c = (self :> c')
 end;;
class c : c'
and d : object method as_c : c' method m : int method n : int end

It is also possible to use a virtual class. Inheriting from this class simultaneously allows to enforce all methods of c to have the same type as the methods of c'.

#class virtual c' = object method virtual m : int end;;
class virtual c' : object method virtual m : int end
 
#class c = object (self) inherit c' method m = 1 end;;
class c : object method m : int end

One could think of defining the type abbreviation directly:

#type c' = <m : int>;;

However, the abbreviation #c' cannot be defined directly in a similar way. It can only be defined by a class or a class-type definition. This is because # sharp abbreviations carry an implicit anonymous variable .. that cannot be explicitly named. The closer you get to it is:

#type 'a c'_class = 'a constraint 'a = < m : int; .. >;;

with an extra type variable capturing the open object type.

3.13  Functional objects

It is possible to write a version of class point without assignments on the instance variables. The construct {< ... >} returns a copy of “self” (that is, the current object), possibly changing the value of some instance variables.

#class functional_point y =
   object 
     val x = y
     method get_x = x
     method move d = {< x = x + d >}
   end;;
class functional_point :
  int ->
  object ('a) val x : int method get_x : int method move : int -> 'a end
 
#let p = new functional_point 7;;
val p : functional_point = <obj>
 
#p#get_x;;
- : int = 7
 
#(p#move 3)#get_x;;
- : int = 10
 
#p#get_x;;
- : int = 7

Note that the type abbreviation functional_point is recursive, which can be seen in the class type of functional_point: the type of self is 'a and 'a appears inside the type of the method move.

The above definition of functional_point is not equivalent to the following:

#class bad_functional_point y =
   object 
     val x = y
     method get_x = x
     method move d = new bad_functional_point (x+d)
   end;;
class bad_functional_point :
  int ->
  object
    val x : int
    method get_x : int
    method move : int -> bad_functional_point
  end

While objects of either class will behave the same, objects of their subclasses will be different. In a subclass of the latter, the method move will keep returning an object of the parent class. On the contrary, in a subclass of the former, the method move will return an object of the subclass.

Functional update is often used in conjunction with binary methods as illustrated in section 5.2.1.

3.14  Cloning objects

Objects can also be cloned, whether they are functional or imperative. The library function Oo.copy makes a shallow copy of an object. That is, it returns an object that is equal to the previous one. The instance variables have been copied but their contents are shared. Assigning a new value to an instance variable of the copy (using a method call) will not affect instance variables of the original, and conversely. A deeper assignment (for example if the instance variable if a reference cell) will of course affect both the original and the copy.

The type of Oo.copy is the following:

#Oo.copy;;
- : (< .. > as 'a) -> 'a = <fun>

The keyword as in that type binds the type variable 'a to the object type < .. >. Therefore, Oo.copy takes an object with any methods (represented by the ellipsis), and returns an object of the same type. The type of Oo.copy is different from type < .. > -> < .. > as each ellipsis represents a different set of methods. Ellipsis actually behaves as a type variable.

#let p = new point 5;;
val p : point = <obj>
 
#let q = Oo.copy p;;
val q : point = <obj>
 
#q#move 7; (p#get_x, q#get_x);;
- : int * int = (5, 12)

In fact, Oo.copy p will behave as p#copy assuming that a public method copy with body {< >} has been defined in the class of p.

Objects can be compared using the generic comparison functions = and <>. Two objects are equal if and only if they are physically equal. In particular, an object and its copy are not equal.

#let q = Oo.copy p;;
val q : point = <obj>
 
#p = q, p = p;;
- : bool * bool = (false, true)

Other generic comparissons such as (<, <=,...) can also be used on objects. The relation < defines an unspecified but strict ordering on objets. The ordering relationship between two objects is fixed once for all after the two objects have been created and it is not affected by mutation of fields.

Cloning and override have a non empty intersection. They are interchangeable when used within an object and without overriding any field:

#class copy =
   object
     method copy = {< >}
   end;;
class copy : object ('a) method copy : 'a end
 
#class copy =
   object (self)
     method copy = Oo.copy self
   end;;
class copy : object ('a) method copy : 'a end

Only the override can be used to actually override fields, and only the Oo.copy primitive can be used externally.

Cloning can also be used to provide facilities for saving and restoring the state of objects.

#class backup = 
   object (self : 'mytype)
     val mutable copy = None
     method save = copy <- Some {< copy = None >}
     method restore = match copy with Some x -> x | None -> self
   end;;
class backup :
  object ('a)
    val mutable copy : 'a option
    method restore : 'a
    method save : unit
  end

The above definition will only backup one level. The backup facility can be added to any class using multiple inheritance.

#class ['a] backup_ref x = object inherit ['a] ref x inherit backup end;;
class ['a] backup_ref :
  'a ->
  object ('b)
    val mutable copy : 'b option
    val mutable x : 'a
    method get : 'a
    method restore : 'b
    method save : unit
    method set : 'a -> unit
  end
 
#let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);;
val get : (< get : 'b; restore : 'a; .. > as 'a) -> int -> 'b = <fun>
 
#let p = new backup_ref 0  in
 p # save; p # set 1; p # save; p # set 2; 
 [get p 0; get p 1; get p 2; get p 3; get p 4];;
- : int list = [2; 1; 1; 1; 1]

A variant of backup could retain all copies. (We then add a method clear to manually erase all copies.)

#class backup = 
   object (self : 'mytype)
     val mutable copy = None
     method save = copy <- Some {< >}
     method restore = match copy with Some x -> x | None -> self
     method clear = copy <- None
   end;;
class backup :
  object ('a)
    val mutable copy : 'a option
    method clear : unit
    method restore : 'a
    method save : unit
  end
#class ['a] backup_ref x = object inherit ['a] ref x inherit backup end;;
class ['a] backup_ref :
  'a ->
  object ('b)
    val mutable copy : 'b option
    val mutable x : 'a
    method clear : unit
    method get : 'a
    method restore : 'b
    method save : unit
    method set : 'a -> unit
  end
 
#let p = new backup_ref 0  in
 p # save; p # set 1; p # save; p # set 2; 
 [get p 0; get p 1; get p 2; get p 3; get p 4];;
- : int list = [2; 1; 0; 0; 0]

3.15  Recursive classes

Recursive classes can be used to define objects whose types are mutually recursive.

#class window =
   object 
     val mutable top_widget = (None : widget option)
     method top_widget = top_widget
   end
 and widget (w : window) =
   object
     val window = w
     method window = window
   end;;
class window :
  object
    val mutable top_widget : widget option
    method top_widget : widget option
  end
and widget : window -> object val window : window method window : window end

Although their types are mutually recursive, the classes widget and window are themselves independent.

3.16  Binary methods

A binary method is a method which takes an argument of the same type as self. The class comparable below is a template for classes with a binary method leq of type 'a -> bool where the type variable 'a is bound to the type of self. Therefore, #comparable expands to < leq : 'a -> bool; .. > as 'a. We see here that the binder as also allows to write recursive types.

#class virtual comparable = 
   object (_ : 'a)
     method virtual leq : 'a -> bool
   end;;
class virtual comparable : object ('a) method virtual leq : 'a -> bool end

We then define a subclass money of comparable. The class money simply wraps floats as comparable objects. We will extend it below with more operations. There is a type constraint on the class parameter x as the primitive <= is a polymorphic comparison function in Objective Caml. The inherit clause ensures that the type of objects of this class is an instance of #comparable.

#class money (x : float) =
   object
     inherit comparable
     val repr = x
     method value = repr
     method leq p = repr <= p#value
   end;;
class money :
  float ->
  object ('a)
    val repr : float
    method leq : 'a -> bool
    method value : float
  end

Note that the type money1 is not a subtype of type comparable, as the self type appears in contravariant position in the type of method leq. Indeed, an object m of class money has a method leq that expects an argument of type money since it accesses its value method. Considering m of type comparable would allow to call method leq on m with an argument that does not have a method value, which would be an error.

Similarly, the type money2 below is not a subtype of type money.

#class money2 x =
   object   
     inherit money x
     method times k = {< repr = k *. repr >}
   end;;
class money2 :
  float ->
  object ('a)
    val repr : float
    method leq : 'a -> bool
    method times : float -> 'a
    method value : float
  end

It is however possible to define functions that manipulate objects of type either money or money2: the function min will return the minimum of any two objects whose type unifies with #comparable. The type of min is not the same as #comparable -> #comparable -> #comparable, as the abbreviation #comparable hides a type variable (an ellipsis). Each occurrence of this abbreviation generates a new variable.

#let min (x : #comparable) y =
   if x#leq y then x else y;;
val min : (#comparable as 'a) -> 'a -> 'a = <fun>

This function can be applied to objects of type money or money2.

#(min (new money  1.3) (new money 3.1))#value;;
- : float = 1.3
 
#(min (new money2 5.0) (new money2 3.14))#value;;
- : float = 3.14

More examples of binary methods can be found in sections 5.2.1 and 5.2.3.

Notice the use of functional update for method times. Writing new money2 (k *. repr) instead of {< repr = k *. repr >} would not behave well with inheritance: in a subclass money3 of money2 the times method would return an object of class money2 but not of class money3 as would be expected.

The class money could naturally carry another binary method. Here is a direct definition:

#class money x =
   object (self : 'a)
     val repr = x
     method value = repr
     method print = print_float repr
     method times k = {< repr = k *. x >}
     method leq (p : 'a) = repr <= p#value
     method plus (p : 'a) = {< repr = x +. p#value >}
   end;;
class money :
  float ->
  object ('a)
    val repr : float
    method leq : 'a -> bool
    method plus : 'a -> 'a
    method print : unit
    method times : float -> 'a
    method value : float
  end

3.17  Friends

The above class money reveals a problem that often occurs with binary methods. In order to interact with other objects of the same class, the representation of money objects must be revealed, using a method such as value. If we remove all binary methods (here plus and leq), the representation can easily be hidden inside objects by removing the method value as well. However, this is not possible as long as some binary requires access to the representation on object of the same class but different from self.

#class safe_money x =
   object (self : 'a)
     val repr = x
     method print = print_float repr
     method times k = {< repr = k *. x >}
   end;;
class safe_money :
  float ->
  object ('a)
    val repr : float
    method print : unit
    method times : float -> 'a
  end

Here, the representation of the object is known only to a particular object. To make it available to other objects of the same class, we are forced to make it available to the whole world. However we can easily restrict the visibility of the representation using the module system.

#module type MONEY = 
   sig 
     type t
     class c : float -> 
       object ('a)
         val repr : t
         method value : t
         method print : unit
         method times : float -> 'a
         method leq : 'a -> bool
         method plus : 'a -> 'a 
       end
   end;;
 
 module Euro : MONEY = 
   struct
     type t = float
     class c x =
       object (self : 'a)
         val repr = x
         method value = repr
         method print = print_float repr
         method times k = {< repr = k *. x >}
         method leq (p : 'a) = repr <= p#value
         method plus (p : 'a) = {< repr = x +. p#value >}
       end
   end;;

Another example of friend functions may be found in section 5.2.3. These examples occur when a group of objects (here objects of the same class) and functions should see each others internal representation, while their representation should be hidden from the outside. The solution is always to define all friends in the same module, give access to the representation and use a signature constraint to make the representation abstract outside of the module.

Chapter 4  Labels and variants

(Chapter written by Jacques Garrigue)



This chapter gives an overview of the new features in Objective Caml 3: labels, and polymorphic variants.

4.1  Labels

If you have a look at modules ending in Labels in the standard library, you will see that function types have annotations you did not have in the functions you defined yourself.

#ListLabels.map;;
- : f:('a -> 'b) -> 'a list -> 'b list = <fun>
 
#StringLabels.sub;;
- : string -> pos:int -> len:int -> string = <fun>

Such annotations of the form name: are called labels. They are meant to document the code, allow more checking, and give more flexibility to function application. You can give such names to arguments in your programs, by prefixing them with a tilde ~.

#let f ~x ~y = x - y;;
val f : x:int -> y:int -> int = <fun>
 
#let x = 3 and y = 2 in f ~x ~y;;
- : int = 1

When you want to use distinct names for the variable and the label appearing in the type, you can use a naming label of the form ~name:. This also applies when the argument is not a variable.

#let f ~x:x1 ~y:y1 = x1 - y1;;
val f : x:int -> y:int -> int = <fun>
 
#f ~x:3 ~y:2;;
- : int = 1

Labels obey the same rules as other identifiers in Caml, that is you cannot use a reserved keyword (like in or to) as label.

Formal parameters and arguments are matched according to their respective labels1, the absence of label being interpreted as the empty label. This allows commuting arguments in applications. One can also partially apply a function on any argument, creating a new function of the remaining parameters.

#let f ~x ~y = x - y;;
val f : x:int -> y:int -> int = <fun>
 
#f ~y:2 ~x:3;;
- : int = 1
 
#ListLabels.fold_left;;
- : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun>
 
#ListLabels.fold_left [1;2;3] ~init:0 ~f:(+);;
- : int = 6
 
#ListLabels.fold_left ~init:0;;
- : f:(int -> 'a -> int) -> 'a list -> int = <fun>

If in a function several arguments bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.

#let hline ~x:x1 ~x:x2 ~y = (x1, x2, y);;
val hline : x:'a -> x:'b -> y:'c -> 'a * 'b * 'c = <fun>
 
#hline ~x:3 ~y:2 ~x:5;;
- : int * int * int = (3, 5, 2)

As an exception to the above parameter matching rules, if an application is total, labels may be omitted. In practice, most applications are total, so that labels can be omitted in applications.

#f 3 2;;
- : int = 1
 
#ListLabels.map succ [1;2;3];;
- : int list = [2; 3; 4]

But beware that functions like ListLabels.fold_left whose result type is a type variable will never be considered as totally applied.

#ListLabels.fold_left (+) 0 [1;2;3];;
This expression has type int -> int -> int but is here used with type 'a list

When a function is passed as an argument to an higher-order function, labels must match in both types. Neither adding nor removing labels are allowed.

#let h g = g ~x:3 ~y:2;;
val h : (x:int -> y:int -> 'a) -> 'a = <fun>
 
#h f;;
- : int = 1
 
#h (+);;
This expression has type int -> int -> int but is here used with type
  x:int -> y:int -> 'a

Note that when you don't need an argument, you can still use a wildcard pattern, but you must prefix it with the label.

#h (fun ~x:_ ~y -> y+1);;
- : int = 3

4.1.1  Optional arguments

An interesting feature of labeled arguments is that they can be made optional. For optional parameters, the question mark ? replaces the tilde ~ of non-optional ones, and the label is also prefixed by ? in the function type. Default values may be given for such optional parameters.

#let bump ?(step = 1) x = x + step;;
val bump : ?step:int -> int -> int = <fun>
 
#bump 2;;
- : int = 3
 
#bump ~step:3 2;;
- : int = 5

A function taking some optional arguments must also take at least one non-labeled argument. This is because the criterion for deciding whether an optional has been omitted is the application on a non-labeled argument appearing after this optional argument in the function type.

#let test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);;
val test : ?x:int -> ?y:int -> unit -> ?z:int -> unit -> int * int * int =
  <fun>
 
#test ();;
- : ?z:int -> unit -> int * int * int = <fun>
 
#test ~x:2 () ~z:3 ();;
- : int * int * int = (2, 0, 3)

Optional parameters may also commute with non-optional or unlabelled ones, as long as they are applied simultaneously. By nature, optional arguments do not commute with unlabeled arguments applied independently.

#test ~y:2 ~x:3 () ();;
- : int * int * int = (3, 2, 0)
 
#test () () ~z:1 ~y:2 ~x:3;;
- : int * int * int = (3, 2, 1)
 
#(test () ()) ~z:1;;
This expression is not a function, it cannot be applied

Here (test () ()) is already (0,0,0) and cannot be further applied.

Optional arguments are actually implemented as option types. If you do not give a default value, you have access to their internal representation, type 'a option = None | Some of 'a. You can then provide different behaviors when an argument is present or not.

#let bump ?step x =
   match step with
   | None -> x * 2
   | Some y -> x + y
 ;;
val bump : ?step:int -> int -> int = <fun>

It may also be useful to relay an optional argument from a function call to another. This can be done by prefixing the applied argument with ?. This question mark disables the wrapping of optional argument in an option type.

#let test2 ?x ?y () = test ?x ?y () ();;
val test2 : ?x:int -> ?y:int -> unit -> int * int * int = <fun>
 
#test2 ?x:None;;
- : ?y:int -> unit -> int * int * int = <fun>

4.1.2  Labels and type inference

While they provide an increased comfort for writing function applications, labels and optional arguments have the pitfall that they cannot be inferred as completely as the rest of the language.

You can see it in the following two examples.

#let h' g = g ~y:2 ~x:3;;
val h' : (y:int -> x:int -> 'a) -> 'a = <fun>
 
#h' f;;
This expression has type x:int -> y:int -> int but is here used with type
  y:int -> x:int -> 'a
 
#let bump_it bump x =
   bump ~step:2 x;;
val bump_it : (step:int -> 'a -> 'b) -> 'a -> 'b = <fun>
 
#bump_it bump 1;;
This expression has type ?step:int -> int -> int but is here used with type
  step:int -> 'a -> 'b

The first case is simple: g is passed ~y and then ~x, but f expects ~x and then ~y. This is correctly handled if we know the type of g to be x:int -> y:int -> int in advance, but otherwise this causes the above type clash. The simplest workaround is to apply formal parameters in a standard order.

The second example is more subtle: while we intended the argument bump to be of type ?step:int -> int -> int, it is inferred as step:int -> int -> 'a. These two types being incompatible (internally normal and optional arguments are different), a type error occurs when applying bump_it to the real bump.

We will not try here to explain in detail how type inference works. One must just understand that there is not enough information in the above program to deduce the correct type of g or bump. That is, there is no way to know whether an argument is optional or not, or which is the correct order, by looking only at how a function is applied. The strategy used by the compiler is to assume that there are no optional arguments, and that applications are done in the right order.

The right way to solve this problem for optional parameters is to add a type annotation to the argument bump.

#let bump_it (bump : ?step:int -> int -> int) x =
   bump ~step:2 x;;
val bump_it : (?step:int -> int -> int) -> int -> int = <fun>
 
#bump_it bump 1;;
- : int = 3

In practive, such problems appear mostly when using objects whose methods have optional arguments, so that writing the type of object arguments is often a good idea.

Normally the compiler generates a type error if you attempt to pass to a function a parameter whose type is different from the expected one. However, in the specific case where the expected type is a non-labeled function type, and the argument is a function expecting optional parameters, the compiler will attempt to transform the argument to have it match the expected type, by passing None for all optional parameters.

#let twice f (x : int) = f(f x);;
val twice : (int -> int) -> int -> int = <fun>
 
#twice bump 2;;
- : int = 8

This transformation is coherent with the intended semantics, including side-effects. That is, if the application of optional parameters shall produce side-effects, these are delayed until the received function is really applied to an argument.

4.1.3  Suggestions for labeling

Like for names, choosing labels for functions is not an easy task. A good labeling is a labeling which

We explain here the rules we applied when labeling Objective Caml libraries.

To speak in an “object-oriented” way, one can consider that each function has a main argument, its object, and other arguments related with its action, the parameters. To permit the combination of functions through functionals in commuting label mode, the object will not be labeled. Its role is clear by the function itself. The parameters are labeled with names reminding either of their nature or role. Best labels combine in their meaning nature and role. When this is not possible the role is to prefer, since the nature will often be given by the type itself. Obscure abbreviations should be avoided.

ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list
UnixLabels.write : file_descr -> buf:string -> pos:int -> len:int -> unit

When there are several objects of same nature and role, they are all left unlabeled.

ListLabels.iter2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> unit

When there is no preferable object, all arguments are labeled.

StringLabels.blit :
  src:string -> src_pos:int -> dst:string -> dst_pos:int -> len:int -> unit

However, when there is only one argument, it is often left unlabeled.

StringLabels.create : int -> string

This principle also applies to functions of several arguments whose return type is a type variable, as long as the role of each argument is not ambiguous. Labeling such functions may lead to awkward error messages when one attempts to omit labels in an application, as we have seen with ListLabels.fold_left.

Here are some of the label names you will find throughout the libraries.

LabelMeaning
f:a function to be applied
pos:a position in a string or array
len:a length
buf:a string used as buffer
src:the source of an operation
dst:the destination of an operation
init:the initial value for an iterator
cmp:a comparison function, e.g. Pervasives.compare
mode:an operation mode or a flag list

All these are only suggestions, but one shall keep in mind that the choice of labels is essential for readability. Bizarre choices will make the program harder to maintain.

In the ideal, the right function name with right labels shall be enough to understand the function's meaning. Since one can get this information with OCamlBrowser or the ocaml toplevel, the documentation is only used when a more detailed specification is needed.

4.2  Polymorphic variants

Variants as presented in section 1.4 are a powerful tool to build data structures and algorithms. However they sometimes lack flexibility when used in modular programming. This is due to the fact every constructor reserves a name to be used with a unique type. One cannot use the same name in another type, or consider a value of some type to belong to some other type with more constructors.

With polymorphic variants, this original assumption is removed. That is, a variant tag does not belong to any type in particular, the type system will just check that it is an admissible value according to its use. You need not define a type before using a variant tag. A variant type will be inferred independently for each of its uses.

Basic use

In programs, polymorphic variants work like usual ones. You just have to prefix their names with a backquote character `.

#[`On; `Off];;
- : [> `Off | `On ] list = [`On; `Off]
 
#`Number 1;;
- : [> `Number of int ] = `Number 1
 
#let f = function `On -> 1 | `Off -> 0 | `Number n -> n;;
val f : [< `Number of int | `Off | `On ] -> int = <fun>
 
#List.map f [`On; `Off];;
- : int list = [1; 0]

[>`Off|`On] list means that to match this list, you should at least be able to match `Off and `On, without argument. [<`On|`Off|`Number of int] means that f may be applied to `Off, `On (both without argument), or `Number n where n is an integer. The > and < inside the variant type shows that they may still be refined, either by defining more tags or allowing less. As such they contain an implicit type variable. Both variant types appearing only once in the type, the implicit type variables they constrain are not shown.

The above variant types were polymorphic, allowing further refinement. When writing type annotations, one will most often describe fixed variant types, that is types that can be no longer refined. This is also the case for type abbreviations. Such types do not contain < or >, but just an enumeration of the tags and their associated types, just like in a normal datatype definition.

#type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];;
type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
 
#let rec map f : 'a vlist -> 'b vlist = function
   | `Nil -> `Nil
   | `Cons(a, l) -> `Cons(f a, map f l)
 ;;
val map : ('a -> 'b) -> 'a vlist -> 'b vlist = <fun>

Advanced use

Type-checking polymorphic variants is a subtle thing, and some expressions may result in more complex type information.

#let f = function `A -> `C | `B -> `D | x -> x;;
val f : ([> `A | `B | `C | `D ] as 'a) -> 'a = <fun>
 
#f `E;;
- : [> `A | `B | `C | `D | `E ] = `E

Here we are seeing two phenomena. First, since this matching is open (the last case catches any tag), we obtain the type [> `A | `B] rather than [< `A | `B] in a closed matching. Then, since x is returned as is, input and return types are identical. The notation as 'a denotes such type sharing. If we apply f to yet another tag `E, it gets added to the list.

#let f1 = function `A x -> x = 1 | `B -> true | `C -> false
 let f2 = function `A x -> x = "a" | `B -> true ;;
val f1 : [< `A of int | `B | `C ] -> bool = <fun>
val f2 : [< `A of string | `B ] -> bool = <fun>
 
#let f x = f1 x && f2 x;;
val f : [< `A of string & int | `B ] -> bool = <fun>

Here f1 and f2 both accept the variant tags `A and `B, but the argument of `A is int for f1 and string for f2. In f's type `C, only accepted by f1, disappears, but both argument types appear for `A as int & string. This means that if we pass the variant tag `A to f, its argument should be both int and string. Since there is no such value, f cannot be applied to `A, and `B is the only accepted input.

Even if a value has a fixed variant type, one can still give it a larger type through coercions. Coercions are normally written with both the source type and the destination type, but in simple cases the source type may be omitted.

#type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];;
type 'a wlist = [ `Cons of 'a * 'a wlist | `Nil | `Snoc of 'a wlist * 'a ]
 
#let wlist_of_vlist  l = (l : 'a vlist :> 'a wlist);;
val wlist_of_vlist : 'a vlist -> 'a wlist = <fun>
 
#let open_vlist l = (l : 'a vlist :> [> 'a vlist]);;
val open_vlist : 'a vlist -> [> 'a vlist ] = <fun>
 
#fun x -> (x :> [`A|`B|`C]);;
- : [< `A | `B | `C ] -> [ `A | `B | `C ] = <fun>

You may also selectively coerce values through pattern matching.

#let split_cases = function
   | `Nil | `Cons _ as x -> `A x
   | `Snoc _ as x -> `B x
 ;;
val split_cases :
  [< `Cons of 'a | `Nil | `Snoc of 'b ] ->
  [> `A of [> `Cons of 'a | `Nil ] | `B of [> `Snoc of 'b ] ] = <fun>

When an or-pattern composed of variant tags is wrapped inside an alias-pattern, the alias is given a type containing only the tags enumerated in the or-pattern. This allows for many useful idioms, like incremental definition of functions.

#let num x = `Num x
 let eval1 eval (`Num x) = x
 let rec eval x = eval1 eval x ;;
val num : 'a -> [> `Num of 'a ] = <fun>
val eval1 : 'a -> [< `Num of 'b ] -> 'b = <fun>
val eval : [< `Num of 'a ] -> 'a = <fun>
 
#let plus x y = `Plus(x,y)
 let eval2 eval = function
   | `Plus(x,y) -> eval x + eval y
   | `Num _ as x -> eval1 eval x
 let rec eval x = eval2 eval x ;;
val plus : 'a -> 'b -> [> `Plus of 'a * 'b ] = <fun>
val eval2 : ('a -> int) -> [< `Num of int | `Plus of 'a * 'a ] -> int = <fun>
val eval : ([< `Num of int | `Plus of 'a * 'a ] as 'a) -> int = <fun>

To make this even more confortable, you may use type definitions as abbreviations for or-patterns. That is, if you have defined type myvariant = [`Tag1 int | `Tag2 bool], then the pattern #myvariant is equivalent to writing (`Tag1(_ : int) | `Tag2(_ : bool)).

Such abbreviations may be used alone,

#let f = function
   | #myvariant -> "myvariant"
   | `Tag3 -> "Tag3";;
val f : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>

or combined with with aliases.

#let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";;
val g1 : [< `Tag1 of 'a | `Tag2 of 'b ] -> string = <fun>
 
#let g = function
   | #myvariant as x -> g1 x
   | `Tag3 -> "Tag3";;
val g : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>

4.2.1  Weaknesses of polymorphic variants

After seeing the power of polymorphic variants, one may wonder why they were added to core language variants, rather than replacing them.

The answer is two fold. One first aspect is that while being pretty efficient, the lack of static type information allows for less optimizations, and makes polymorphic variants slightly heavier than core language ones. However noticeable differences would only appear on huge data structures.

More important is the fact that polymorphic variants, while being type-safe, result in a weaker type discipline. That is, core language variants do actually much more than ensuring type-safety, they also check that you use only declared constructors, that all constructors present in a data-structure are compatible, and they enforce typing constraints to their parameters.

For this reason, you must be more careful about making types explicit when you use polymorphic variants. When you write a library, this is easy since you can describe exact types in interfaces, but for simple programs you are probably better off with core language variants.

Beware also that some idioms make trivial errors very hard to find. For instance, the following code is probably wrong but the compiler has no way to see it.

#type abc = [`A | `B | `C] ;;
type abc = [ `A | `B | `C ]
 
#let f = function
   | `As -> "A"
   | #abc -> "other" ;;
val f : [< `A | `As | `B | `C ] -> string = <fun>
 
#let f : abc -> string = f ;;
val f : abc -> string = <fun>

You can avoid such risks by annotating the definition itself.

#let f : abc -> string = function
   | `As -> "A"
   | #abc -> "other" ;;
Warning U: this match case is unused.
val f : abc -> string = <fun>

1
This correspond to the commuting label mode of Objective Caml 3.00 through 3.02, with some additional flexibility on total applications. The so-called classic mode (-nolabels options) is now deprecated for normal use.

Chapter 5  Advanced examples with classes and modules

(Chapter written by Didier Rémy)



In this chapter, we show some larger examples using objects, classes and modules. We review many of the object features simultaneously on the example of a bank account. We show how modules taken from the standard library can be expressed as classes. Lastly, we describe a programming pattern know of as virtual types through the example of window managers.

5.1  Extended example: bank accounts

In this section, we illustrate most aspects of Object and inheritance by refining, debugging, and specializing the following initial naive definition of a simple bank account. (We reuse the module Euro defined at the end of chapter 3.)

#let euro = new Euro.c;;
val euro : float -> Euro.c = <fun>
 
#let zero = euro 0.;;
val zero : Euro.c = <obj>
 
#let neg x = x#times (-1.);;
val neg : < times : float -> 'a; .. > -> 'a = <fun>
 
#class account =
   object 
     val mutable balance = zero
     method balance = balance
     method deposit x = balance <- balance # plus x
     method withdraw x =
       if x#leq balance then (balance <- balance # plus (neg x); x) else zero
   end;;
class account :
  object
    val mutable balance : Euro.c
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method withdraw : Euro.c -> Euro.c
  end
 
#let c = new account in c # deposit (euro 100.); c # withdraw (euro 50.);;
- : Euro.c = <obj>

We now refine this definition with a method to compute interest.

#class account_with_interests =
   object (self)
     inherit account
     method private interest = self # deposit (self # balance # times 0.03)
   end;;
class account_with_interests :
  object
    val mutable balance : Euro.c
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method private interest : unit
    method withdraw : Euro.c -> Euro.c
  end

We make the method interest private, since clearly it should not be called freely from the outside. Here, it is only made accessible to subclasses that will manage monthly or yearly updates of the account.

We should soon fix a bug in the current definition: the deposit method can be used for withdrawing money by depositing negative amounts. We can fix this directly:

#class safe_account =
   object
     inherit account
     method deposit x = if zero#leq x then balance <- balance#plus x
   end;;
class safe_account :
  object
    val mutable balance : Euro.c
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method withdraw : Euro.c -> Euro.c
  end

However, the bug might be fixed more safely by the following definition:

#class safe_account =
   object
     inherit account as unsafe
     method deposit x =
       if zero#leq x then unsafe # deposit x
       else raise (Invalid_argument "deposit")
   end;;
class safe_account :
  object
    val mutable balance : Euro.c
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method withdraw : Euro.c -> Euro.c
  end

In particular, this does not require the knowledge of the implementation of the method deposit.

To keep trace of operations, we extend the class with a mutable field history and a private method trace to add an operation in the log. Then each method to be traced is redefined.

#type 'a operation = Deposit of 'a | Retrieval of 'a;;
type 'a operation = Deposit of 'a | Retrieval of 'a
 
#class account_with_history =
   object (self) 
     inherit safe_account as super  
     val mutable history = []
     method private trace x = history <- x :: history
     method deposit x = self#trace (Deposit x);  super#deposit x
     method withdraw x = self#trace (Retrieval x); super#withdraw x
     method history = List.rev history
   end;;
class account_with_history :
  object
    val mutable balance : Euro.c
    val mutable history : Euro.c operation list
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method history : Euro.c operation list
    method private trace : Euro.c operation -> unit
    method withdraw : Euro.c -> Euro.c
  end

One may wish to open an account and simultaneously deposit some initial amount. Although the initial implementation did not address this requirement, it can be achieved by using an initializer.

#class account_with_deposit x =
   object 
     inherit account_with_history 
     initializer balance <- x 
   end;;
class account_with_deposit :
  Euro.c ->
  object
    val mutable balance : Euro.c
    val mutable history : Euro.c operation list
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method history : Euro.c operation list
    method private trace : Euro.c operation -> unit
    method withdraw : Euro.c -> Euro.c
  end

A better alternative is:

#class account_with_deposit x =
   object (self)
     inherit account_with_history 
     initializer self#deposit x
   end;;
class account_with_deposit :
  Euro.c ->
  object
    val mutable balance : Euro.c
    val mutable history : Euro.c operation list
    method balance : Euro.c
    method deposit : Euro.c -> unit
    method history : Euro.c operation list
    method private trace : Euro.c operation -> unit
    method withdraw : Euro.c -> Euro.c
  end

Indeed, the latter is safer since the call to deposit will automatically benefit from safety checks and from the trace. Let's test it:

#let ccp = new account_with_deposit (euro 100.) in 
 let balance = ccp#withdraw (euro 50.) in
 ccp#history;;
Warning Y: unused variable balance.
- : Euro.c operation list = [Deposit <obj>; Retrieval <obj>]

Closing an account can be done with the following polymorphic function:

#let close c = c#withdraw (c#balance);;
val close : < balance : 'a; withdraw : 'a -> 'b; .. > -> 'b = <fun>

Of course, this applies to all sorts of accounts.

Finally, we gather several versions of the account into a module Account abstracted over some currency.

#let today () = (01,01,2000) (* an approximation *)
 module Account (M:MONEY) =
   struct
     type m = M.c
     let m = new M.c
     let zero = m 0. 
         
     class bank =
       object (self) 
         val mutable balance = zero
         method balance = balance
         val mutable history = []
         method private trace x = history <- x::history
         method deposit x =
           self#trace (Deposit x);
           if zero#leq x then balance <- balance # plus x
           else raise (Invalid_argument "deposit")
         method withdraw x =
           if x#leq balance then
             (balance <- balance # plus (neg x); self#trace (Retrieval x); x)
           else zero
         method history = List.rev history
       end
         
     class type client_view = 
       object
         method deposit : m -> unit
         method history : m operation list
         method withdraw : m -> m
         method balance : m
       end
           
     class virtual check_client x = 
       let y = if (m 100.)#leq x then x
       else raise (Failure "Insufficient initial deposit") in
       object (self) initializer self#deposit y end
         
     module Client (B : sig class bank : client_view end) =
       struct
         class account x : client_view =
           object
             inherit B.bank
             inherit check_client x
           end
             
         let discount x =
           let c = new account x in
           if today() < (1998,10,30) then c # deposit (m 100.); c
       end
   end;;

This shows the use of modules to group several class definitions that can in fact be thought of as a single unit. This unit would be provided by a bank for both internal and external uses. This is implemented as a functor that abstracts over the currency so that the same code can be used to provide accounts in different currencies.

The class bank is the real implementation of the bank account (it could have been inlined). This is the one that will be used for further extensions, refinements, etc. Conversely, the client will only be given the client view.

#module Euro_account = Account(Euro);;
 
 module Client = Euro_account.Client (Euro_account);;
 
 new Client.account (new Euro.c 100.);;

Hence, the clients do not have direct access to the balance, nor the history of their own accounts. Their only way to change their balance is to deposit or withdraw money. It is important to give the clients a class and not just the ability to create accounts (such as the promotional discount account), so that they can personalize their account. For instance, a client may refine the deposit and withdraw methods so as to do his own financial bookkeeping, automatically. On the other hand, the function discount is given as such, with no possibility for further personalization.

It is important that to provide the client's view as a functor Client so that client accounts can still be build after a possible specialization of the bank. The functor Client may remain unchanged and be passed the new definition to initialize a client's view of the extended account.

#module Investment_account (M : MONEY) = 
   struct
     type m = M.c
     module A = Account(M)
         
     class bank =
       object
         inherit A.bank as super
         method deposit x =
           if (new M.c 1000.)#leq x then
             print_string "Would you like to invest?";
           super#deposit x
       end
         
     module Client = A.Client
   end;;

The functor Client may also be redefined when some new features of the account can be given to the client.

#module Internet_account (M : MONEY) = 
   struct
     type m = M.c
     module A = Account(M)

     class bank =
       object
         inherit A.bank 
         method mail s = print_string s
       end
         
     class type client_view = 
       object
         method deposit : m -> unit
         method history : m operation list
         method withdraw : m -> m
         method balance : m
         method mail : string -> unit
       end
           
     module Client (B : sig class bank : client_view end) =
       struct
         class account x : client_view =
           object
             inherit B.bank
             inherit A.check_client x
           end
       end
   end;;

5.2  Simple modules as classes

One may wonder whether it is possible to treat primitive types such as integers and strings as objects. Although this is usually uninteresting for integers or strings, there may be some situations where this is desirable. The class money above is such an example. We show here how to do it for strings.

5.2.1  Strings

A naive definition of strings as objects could be:

#class ostring s =
   object
      method get n = String.get s n
      method set n c = String.set s n c
      method print = print_string s
      method copy = new ostring (String.copy s)
   end;;
class ostring :
  string ->
  object
    method copy : ostring
    method get : int -> char
    method print : unit
    method set : int -> char -> unit
  end

However, the method copy returns an object of the class ostring, and not an objet of the current class. Hence, if the class is further extended, the method copy will only return an object of the parent class.

#class sub_string s =
   object
      inherit ostring s
      method sub start len = new sub_string (String.sub s  start len)
   end;;
class sub_string :
  string ->
  object
    method copy : ostring
    method get : int -> char
    method print : unit
    method set : int -> char -> unit
    method sub : int -> int -> sub_string
  end

As seen in section 3.16, the solution is to use functional update instead. We need to create an instance variable containing the representation s of the string.

#class better_string s =
   object
      val repr = s
      method get n = String.get repr n
      method set n c = String.set repr n c
      method print = print_string repr
      method copy = {< repr = String.copy repr >}
      method sub start len = {< repr = String.sub s  start len >}
   end;;
class better_string :
  string ->
  object ('a)
    val repr : string
    method copy : 'a
    method get : int -> char
    method print : unit
    method set : int -> char -> unit
    method sub : int -> int -> 'a
  end

As shown in the inferred type, the methods copy and sub now return objects of the same type as the one of the class.

Another difficulty is the implementation of the method concat. In order to concatenate a string with another string of the same class, one must be able to access the instance variable externally. Thus, a method repr returning s must be defined. Here is the correct definition of strings:

#class ostring s =
   object (self : 'mytype)
      val repr = s
      method repr = repr
      method get n = String.get repr n
      method set n c = String.set repr n c
      method print = print_string repr
      method copy = {< repr = String.copy repr >}
      method sub start len = {< repr = String.sub s start len >}
      method concat (t : 'mytype) = {< repr = repr ^ t#repr >}
   end;;
class ostring :
  string ->
  object ('a)
    val repr : string
    method concat : 'a -> 'a
    method copy : 'a
    method get : int -> char
    method print : unit
    method repr : string
    method set : int -> char -> unit
    method sub : int -> int -> 'a
  end

Another constructor of the class string can be defined to return an uninitialized string of a given length:

#class cstring n = ostring (String.create n);;
class cstring : int -> ostring

Here, exposing the representation of strings is probably harmless. We do could also hide the representation of strings as we hid the currency in the class money of section 3.17.

Stacks

There is sometimes an alternative between using modules or classes for parametric data types. Indeed, there are situations when the two approaches are quite similar. For instance, a stack can be straightforwardly implemented as a class:

#exception Empty;;
exception Empty
 
#class ['a] stack =
   object 
     val mutable l = ([] : 'a list)
     method push x = l <- x::l
     method pop = match l with [] -> raise Empty | a::l' -> l <- l'; a
     method clear = l <- []
     method length = List.length l
   end;;
class ['a] stack :
  object
    val mutable l : 'a list
    method clear : unit
    method length : int
    method pop : 'a
    method push : 'a -> unit
  end

However, writing a method for iterating over a stack is more problematic. A method fold would have type ('b -> 'a -> 'b) -> 'b -> 'b. Here 'a is the parameter of the stack. The parameter 'b is not related to the class 'a stack but to the argument that will be passed to the method fold. A naive approach is to make 'b an extra parameter of class stack:

#class ['a, 'b] stack2 =
   object
     inherit ['a] stack
     method fold f (x : 'b) = List.fold_left f x l
   end;;
class ['a, 'b] stack2 :
  object
    val mutable l : 'a list
    method clear : unit
    method fold : ('b -> 'a -> 'b) -> 'b -> 'b
    method length : int
    method pop : 'a
    method push : 'a -> unit
  end

However, the method fold of a given object can only be applied to functions that all have the same type:

#let s = new stack2;;
val s : ('_a, '_b) stack2 = <obj>
 
#s#fold (+) 0;;
- : int = 0
 
#s;;
- : (int, int) stack2 = <obj>

A better solution is to use polymorphic methods, which were introduced in Objective Caml version 3.05. Polymorphic methods makes it possible to treat the type variable 'b in the type of fold as universally quantified, giving fold the polymorphic type Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b. An explicit type declaration on the method fold is required, since the type checker cannot infer the polymorphic type by itself.

#class ['a] stack3 =
   object
     inherit ['a] stack
     method fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b
                 = fun f x -> List.fold_left f x l
   end;;
class ['a] stack3 :
  object
    val mutable l : 'a list
    method clear : unit
    method fold : ('b -> 'a -> 'b) -> 'b -> 'b
    method length : int
    method pop : 'a
    method push : 'a -> unit
  end

5.2.2  Hashtbl

A simplified version of object-oriented hash tables should have the following class type.

#class type ['a, 'b] hash_table =
   object 
     method find : 'a -> 'b
     method add : 'a -> 'b -> unit
   end;;
class type ['a, 'b] hash_table =
  object method add : 'a -> 'b -> unit method find : 'a -> 'b end

A simple implementation, which is quite reasonable for small hastables is to use an association list:

#class ['a, 'b] small_hashtbl : ['a, 'b] hash_table =
   object
     val mutable table = []
     method find key = List.assoc key table
     method add key valeur = table <- (key, valeur) :: table
   end;;
class ['a, 'b] small_hashtbl : ['a, 'b] hash_table

A better implementation, and one that scales up better, is to use a true hash tables… whose elements are small hash tables!

#class ['a, 'b] hashtbl size : ['a, 'b] hash_table =
   object (self)
     val table = Array.init size (fun i -> new small_hashtbl) 
     method private hash key =
       (Hashtbl.hash key) mod (Array.length table)
     method find key = table.(self#hash key) # find key
     method add key = table.(self#hash key) # add key
   end;;
class ['a, 'b] hashtbl : int -> ['a, 'b] hash_table

5.2.3  Sets

Implementing sets leads to another difficulty. Indeed, the method union needs to be able to access the internal representation of another object of the same class.

This is another instance of friend functions as seen in section 3.17. Indeed, this is the same mechanism used in the module Set in the absence of objects.

In the object-oriented version of sets, we only need to add an additional method tag to return the representation of a set. Since sets are parametric in the type of elements, the method tag has a parametric type 'a tag, concrete within the module definition but abstract in its signature. From outside, it will then be guaranteed that two objects with a method tag of the same type will share the same representation.

#module type SET =
   sig
     type 'a tag
     class ['a] c :
       object ('b)
         method is_empty : bool
         method mem : 'a -> bool
         method add : 'a -> 'b
         method union : 'b -> 'b
         method iter : ('a -> unit) -> unit
         method tag : 'a tag
       end
   end;;
 
 module Set : SET =
   struct
     let rec merge l1 l2 =
       match l1 with
         [] -> l2
       | h1 :: t1 ->
           match l2 with
             [] -> l1
           | h2 :: t2 ->
               if h1 < h2 then h1 :: merge t1 l2
               else if h1 > h2 then h2 :: merge l1 t2
               else merge t1 l2
     type 'a tag = 'a list
     class ['a] c =
       object (_ : 'b)
         val repr = ([] : 'a list)
         method is_empty = (repr = [])
         method mem x = List.exists ((=) x) repr
         method add x = {< repr = merge [x] repr >}
         method union (s : 'b) = {< repr = merge repr s#tag >}
         method iter (f : 'a -> unit) = List.iter f repr
         method tag = repr
       end
   end;;

5.3  The subject/observer pattern

The following example, known as the subject/observer pattern, is often presented in the literature as a difficult inheritance problem with inter-connected classes. The general pattern amounts to the definition a pair of two classes that recursively interact with one another.

The class observer has a distinguished method notify that requires two arguments, a subject and an event to execute an action.

#class virtual ['subject, 'event] observer =
   object
     method virtual notify : 'subject ->  'event -> unit
   end;;
class virtual ['a, 'b] observer :
  object method virtual notify : 'a -> 'b -> unit end

The class subject remembers a list of observers in an instance variable, and has a distinguished method notify_observers to broadcast the message notify to all observers with a particular event e.

#class ['observer, 'event] subject =
   object (self)
     val mutable observers = ([]:'observer list)
     method add_observer obs = observers <- (obs :: observers)
     method notify_observers (e : 'event) = 
         List.iter (fun x -> x#notify self e) observers
   end;;
class ['a, 'b] subject :
  object ('c)
    constraint 'a = < notify : 'c -> 'b -> unit; .. >
    val mutable observers : 'a list
    method add_observer : 'a -> unit
    method notify_observers : 'b -> unit
  end

The difficulty usually relies in defining instances of the pattern above by inheritance. This can be done in a natural and obvious manner in Ocaml, as shown on the following example manipulating windows.

#type event = Raise | Resize | Move;;
type event = Raise | Resize | Move
 
#let string_of_event = function
     Raise -> "Raise" | Resize -> "Resize" | Move -> "Move";;
val string_of_event : event -> string = <fun>
 
#let count = ref 0;;
val count : int ref = {contents = 0}
 
#class ['observer] window_subject =
   let id = count := succ !count; !count in
   object (self)
     inherit ['observer, event] subject
     val mutable position = 0
     method identity = id
     method move x = position <- position + x; self#notify_observers Move
     method draw = Printf.printf "{Position = %d}\n"  position;
   end;;
class ['a] window_subject :
  object ('b)
    constraint 'a = < notify : 'b -> event -> unit; .. >
    val mutable observers : 'a list
    val mutable position : int
    method add_observer : 'a -> unit
    method draw : unit
    method identity : int
    method move : int -> unit
    method notify_observers : event -> unit
  end
 
#class ['subject] window_observer =
   object
     inherit ['subject, event] observer
     method notify s e = s#draw
   end;;
class ['a] window_observer :
  object
    constraint 'a = < draw : unit; .. >
    method notify : 'a -> event -> unit
  end

Unsurprisingly the type of window is recursive.

#let window = new window_subject;;
val window : < notify : 'a -> event -> unit; _.. > window_subject as 'a =
  <obj>

However, the two classes of window_subject and window_observer are not mutually recursive.

#let window_observer = new window_observer;;
val window_observer : < draw : unit; _.. > window_observer = <obj>
 
#window#add_observer window_observer;;
- : unit = ()
 
#window#move 1;;
{Position = 1}
- : unit = ()

Classes window_observer and window_subject can still be extended by inheritance. For instance, one may enrich the subject with new behaviors and refined the behavior of the observer.

#class ['observer] richer_window_subject =
   object (self)
     inherit ['observer] window_subject
     val mutable size = 1
     method resize x = size <- size + x; self#notify_observers Resize
     val mutable top = false
     method raise = top <- true; self#notify_observers Raise
     method draw = Printf.printf "{Position = %d; Size = %d}\n"  position size;
   end;;
class ['a] richer_window_subject :
  object ('b)
    constraint 'a = < notify : 'b -> event -> unit; .. >
    val mutable observers : 'a list
    val mutable position : int
    val mutable size : int
    val mutable top : bool
    method add_observer : 'a -> unit
    method draw : unit
    method identity : int
    method move : int -> unit
    method notify_observers : event -> unit
    method raise : unit
    method resize : int -> unit
  end
 
#class ['subject] richer_window_observer =
   object 
     inherit ['subject] window_observer as super
     method notify s e = if e <> Raise then s#raise; super#notify s e
   end;;
class ['a] richer_window_observer :
  object
    constraint 'a = < draw : unit; raise : unit; .. >
    method notify : 'a -> event -> unit
  end

We can also create a different kind of observer:

#class ['subject] trace_observer = 
   object 
     inherit ['subject, event] observer
     method notify s e =
       Printf.printf
         "<Window %d <== %s>\n" s#identity (string_of_event e)
   end;;
class ['a] trace_observer :
  object
    constraint 'a = < identity : int; .. >
    method notify : 'a -> event -> unit
  end

and attached several observers to the same object:

#let window = new richer_window_subject;;
val window :
  < notify : 'a -> event -> unit; _.. > richer_window_subject as 'a = <obj>
 
#window#add_observer (new richer_window_observer);;
- : unit = ()
 
#window#add_observer (new trace_observer);;
- : unit = ()
 
#window#move 1; window#resize 2;;
<Window 1 <== Move>
<Window 1 <== Raise>
{Position = 1; Size = 1}
{Position = 1; Size = 1}
<Window 1 <== Resize>
<Window 1 <== Raise>
{Position = 1; Size = 3}
{Position = 1; Size = 3}
- : unit = ()

Part II
The Objective Caml language

Chapter 6  The Objective Caml language

Foreword

This document is intended as a reference manual for the Objective Caml language. It lists the language constructs, and gives their precise syntax and informal semantics. It is by no means a tutorial introduction to the language: there is not a single example. A good working knowledge of Caml is assumed.

No attempt has been made at mathematical rigor: words are employed with their intuitive meaning, without further definition. As a consequence, the typing rules have been left out, by lack of the mathematical framework required to express them, while they are definitely part of a full formal definition of the language.

Notations

The syntax of the language is given in BNF-like notation. Terminal symbols are set in typewriter font (like this). Non-terminal symbols are set in italic font (like that). Square brackets […] denote optional components. Curly brackets {…} denotes zero, one or several repetitions of the enclosed components. Curly bracket with a trailing plus sign {…}+ denote one or several repetitions of the enclosed components. Parentheses (…) denote grouping.

6.1  Lexical conventions

Blanks

The following characters are considered as blanks: space, newline, horizontal tabulation, carriage return, line feed and form feed. Blanks are ignored, but they separate adjacent identifiers, literals and keywords that would otherwise be confused as one single identifier, literal or keyword.

Comments

Comments are introduced by the two characters (*, with no intervening blanks, and terminated by the characters *), with no intervening blanks. Comments are treated as blank characters. Comments do not occur inside string or character literals. Nested comments are handled correctly.

Identifiers

ident::= (letter∣ _) { letter∣ 09∣ _∣ ' }  
 
letter::= A … Z ∣  a … z

Identifiers are sequences of letters, digits, _ (the underscore character), and ' (the single quote), starting with a letter or an underscore. Letters contain at least the 52 lowercase and uppercase letters from the ASCII set. The current implementation also recognizes as letters all accented characters from the ISO 8859-1 (“ISO Latin 1”) set. All characters in an identifier are meaningful. The current implementation accepts identifiers up to 16000000 characters in length.

Integer literals

integer-literal::= [-] (09) { 09∣ _ }  
  [-] (0x∣ 0X) (09∣ AF∣ af) { 09∣ AF∣ af∣ _ }  
  [-] (0o∣ 0O) (07) { 07∣ _ }  
  [-] (0b∣ 0B) (01) { 01∣ _ }

An integer literal is a sequence of one or more digits, optionally preceded by a minus sign. By default, integer literals are in decimal (radix 10). The following prefixes select a different radix:

PrefixRadix
0x, 0Xhexadecimal (radix 16)
0o, 0Ooctal (radix 8)
0b, 0Bbinary (radix 2)

(The initial 0 is the digit zero; the O for octal is the letter O.) The interpretation of integer literals that fall outside the range of representable integer values is undefined.

For convenience and readability, underscore characters (_) are accepted (and ignored) within integer literals.

Floating-point literals

float-literal::= [-] (09) { 09∣ _ } [. { 09∣ _ }] [(e∣ E) [+∣ -] (09) { 09∣ _ }]

Floating-point decimals consist in an integer part, a decimal part and an exponent part. The integer part is a sequence of one or more digits, optionally preceded by a minus sign. The decimal part is a decimal point followed by zero, one or more digits. The exponent part is the character e or E followed by an optional + or - sign, followed by one or more digits. The decimal part or the exponent part can be omitted, but not both to avoid ambiguity with integer literals. The interpretation of floating-point literals that fall outside the range of representable floating-point values is undefined.

For convenience and readability, underscore characters (_) are accepted (and ignored) within floating-point literals.

Character literals

char-literal::= ' regular-char '  
  ' escape-sequence '  
 
escape-sequence::= \ (\ ∣  " ∣  ' ∣  n ∣  t ∣  b ∣  r)  
  \ (09) (09) (09)  
  \x (09∣ AF∣ af) (09∣ AF∣ af)

Character literals are delimited by ' (single quote) characters. The two single quotes enclose either one character different from ' and \, or one of the escape sequences below:

SequenceCharacter denoted
\\backslash (\)
\"double quote (")
\'single quote (')
\nlinefeed (LF)
\rcarriage return (CR)
\thorizontal tabulation (TAB)
\bbackspace (BS)
\spacespace (SPC)
\dddthe character with ASCII code ddd in decimal
\xhhthe character with ASCII code hh in hexadecimal

String literals

string-literal::= " { string-character } "  
 
string-character::= regular-char-str  
  escape-sequence

String literals are delimited by " (double quote) characters. The two double quotes enclose a sequence of either characters different from " and \, or escape sequences from the table given above for character literals.

To allow splitting long string literals across lines, the sequence \newline blanks (a \ at end-of-line followed by any number of blanks at the beginning of the next line) is ignored inside string literals.

The current implementation places practically no restrictions on the length of string literals.

Naming labels

To avoid ambiguities, naming labels in expressions cannot just be defined syntactically as the sequence of the three tokens ~, ident and :, and have to be defined at the lexical level.

label-name ::= (a … z∣ _) { letter∣ 09∣ _∣ ' } 
 
label ::= ~ label-name :  
 
optlabel ::= ? label-name :

Naming labels come in two flavours: label for normal arguments and optlabel for optional ones. They are simply distinguished by their first character, either ~ or ?.

Despite label and optlabel being lexical entities in expressions, their expansions ~ label-name : and ? label-name : will be used in grammars, for the sake of readability. Note also that inside type expressions, this expansion can be taken literally, i.e. there are really 3 tokens, with optional spaces beween them.

Prefix and infix symbols

infix-symbol::= (= ∣  < ∣  > ∣  @ ∣  ^ ∣  | ∣  & ∣  + ∣  - ∣  * ∣  / ∣  $ ∣  %) { operator-char }  
 
prefix-symbol::= (! ∣  ? ∣  ~) { operator-char }  
 
operator-char::= ! ∣  $ ∣  % ∣  & ∣  * ∣  + ∣  - ∣  . ∣  / ∣  : ∣  < ∣  = ∣  > ∣  ? ∣  @ ∣  ^ ∣  | ∣  ~  
 

Sequences of “operator characters”, such as <=> or !!, are read as a single token from the infix-symbol or prefix-symbol class. These symbols are parsed as prefix and infix operators inside expressions, but otherwise behave much as identifiers.

Keywords

The identifiers below are reserved as keywords, and cannot be employed otherwise:

      and         as          assert      asr         begin       class
      constraint  do          done        downto      else        end
      exception   external    false       for         fun         function
      functor     if          in          include     inherit     initializer
      land        lazy        let         lor         lsl         lsr
      lxor        match       method      mod         module      mutable
      new         object      of          open        or          private
      rec         sig         struct      then        to          true
      try         type        val         virtual     when        while
      with        

The following character sequences are also keywords:

    !=    #     &     &&    '     (     )     *     +     ,     -
    -.    ->    .     ..    :     ::    :=    :>    ;     ;;    <
    <-    =     >     >]    >}    ?     ??    [     [<    [>    [|
    ]     _     `     {     {<    |     |]    }     ~

Note that the following identifiers are keywords of the Camlp4 extensions and should be avoided for compatibility reasons.

    parser    <<    <:    >>    $     $$    $:

Ambiguities

Lexical ambiguities are resolved according to the “longest match” rule: when a character sequence can be decomposed into two tokens in several different ways, the decomposition retained is the one with the longest first token.

Line number directives

linenum-directive::= # {0 … 9}+  
  # {0 … 9}+ " { string-character } "  
 

Preprocessors that generate Caml source code can insert line number directives in their output so that error messages produced by the compiler contain line numbers and file names referring to the source file before preprocessing, instead of after preprocessing. A line number directive is composed of a # (sharp sign), followed by a positive integer (the source line number), optionally followed by a character string (the source file name). Line number directives are treated as blank characters during lexical analysis.

6.2  Values

This section describes the kinds of values that are manipulated by Objective Caml programs.

6.2.1  Base values

Integer numbers

Integer values are integer numbers from −230 to 230−1, that is −1073741824 to 1073741823. The implementation may support a wider range of integer values: on 64-bit platforms, the current implementation supports integers ranging from −262 to 262−1.

Floating-point numbers

Floating-point values are numbers in floating-point representation. The current implementation uses double-precision floating-point numbers conforming to the IEEE 754 standard, with 53 bits of mantissa and an exponent ranging from −1022 to 1023.

Characters

Character values are represented as 8-bit integers between 0 and 255. Character codes between 0 and 127 are interpreted following the ASCII standard. The current implementation interprets character codes between 128 and 255 following the ISO 8859-1 standard.

Character strings

String values are finite sequences of characters. The current implementation supports strings containing up to 224 − 5 characters (16777211 characters); on 64-bit platforms, the limit is 257 − 9.

6.2.2  Tuples

Tuples of values are written (v1, …, vn), standing for the n-tuple of values v1 to vn. The current implementation supports tuple of up to 222 − 1 elements (4194303 elements).

6.2.3  Records

Record values are labeled tuples of values. The record value written { field1 = v1; …; fieldn = vn } associates the value vi to the record field fieldi, for i = 1 … n. The current implementation supports records with up to 222 − 1 fields (4194303 fields).

6.2.4  Arrays

Arrays are finite, variable-sized sequences of values of the same type. The current implementation supports arrays containing up to 222 − 1 elements (4194303 elements) unless the elements are floating-point numbers (2097151 elements in this case); on 64-bit platforms, the limit is 254 − 1 for all arrays.

6.2.5  Variant values

Variant values are either a constant constructor, or a pair of a non-constant constructor and a value. The former case is written constr; the latter case is written constr(v), where v is said to be the argument of the non-constant constructor constr.

The following constants are treated like built-in constant constructors:

ConstantConstructor
falsethe boolean false
truethe boolean true
()the “unit” value
[]the empty list

The current implementation limits each variant type to have at most 246 non-constant constructors.

6.2.6  Polymorphic variants

Polymorphic variants are an alternate form of variant values, not belonging explicitly to a predefined variant type, and following specific typing rules. They can be either constant, written `tag-name, or non-constant, written `tag-name(v).

6.2.7  Functions

Functional values are mappings from values to values.

6.2.8  Objects

Objects are composed of a hidden internal state which is a record of instance variables, and a set of methods for accessing and modifying these variables. The structure of an object is described by the toplevel class that created it.

6.3  Names

Identifiers are used to give names to several classes of language objects and refer to these objects by name later:

These eleven name spaces are distinguished both by the context and by the capitalization of the identifier: whether the first letter of the identifier is in lowercase (written lowercase-ident below) or in uppercase (written capitalized-ident). Underscore is considered a lowercase letter for this purpose.

Naming objects

value-name::= lowercase-ident  
  ( operator-name )  
 
operator-name::= prefix-symbol ∣  infix-op  
 
infix-op::= infix-symbol  
  * ∣  = ∣  or ∣  & ∣  :=  
  mod ∣  land ∣  lor ∣  lxor ∣  lsl ∣  lsr ∣  asr  
 
constr-name::= capitalized-ident  
 
label-name::= lowercase-ident  
 
tag-name::= capitalized-ident  
 
typeconstr-name::= lowercase-ident  
 
field-name::= lowercase-ident  
 
module-name::= capitalized-ident  
 
modtype-name::= ident  
 
class-name::= lowercase-ident  
 
inst-var-name::= lowercase-ident  
 
method-name::= lowercase-ident

As shown above, prefix and infix symbols as well as some keywords can be used as value names, provided they are written between parentheses. The capitalization rules are summarized in the table below.

Name spaceCase of first letter
Valueslowercase
Constructorsuppercase
Labelslowercase
Variant tagsuppercase
Exceptionsuppercase
Type constructorslowercase
Record fieldslowercase
Classeslowercase
Instance variableslowercase
Methodslowercase
Modulesuppercase
Module typesany

Note on variant tags: the current implementation accepts lowercase variant tags in addition to uppercase variant tags, but we suggest you avoid lowercase variant tags for portability and compatibility with future OCaml versions.

Referring to named objects

value-path::= value-name  
  module-path .  value-name  
 
constr::= constr-name  
  module-path .  constr-name  
 
typeconstr::= typeconstr-name  
  extended-module-path .  typeconstr-name  
 
field::= field-name  
  module-path .  field-name  
 
module-path::= module-name  
  module-path .  module-name  
 
extended-module-path::= module-name  
  extended-module-path .  module-name  
  extended-module-path (  extended-module-path )  
 
modtype-path::= modtype-name  
  extended-module-path .  modtype-name  
 
class-path::= class-name  
  module-path .  class-name

A named object can be referred to either by its name (following the usual static scoping rules for names) or by an access path prefix .  name, where prefix designates a module and name is the name of an object defined in that module. The first component of the path, prefix, is either a simple module name or an access path name1 .  name2 …, in case the defining module is itself nested inside other modules. For referring to type constructors or module types, the prefix can also contain simple functor applications (as in the syntactic class extended-module-path above), in case the defining module is the result of a functor application.

Label names, tag names, method names and instance variable names need not be qualified: the former three are global labels, while the latter are local to a class.

6.4  Type expressions

typexpr::= ' ident  
  _   
  ( typexpr )  
  [[?]label-name:]  typexpr ->  typexpr  
  typexpr  { * typexpr }+  
  typeconstr  
  typexpr  typeconstr  
  ( typexpr  { , typexpr } )  typeconstr  
  typexpr as '  ident  
  variant-type  
  < [..>  
  < method-type  { ; method-type }  [; ..>  
  # class-path  
  typexpr #  class-path  
  ( typexpr  { , typexpr } ) #  class-path  
 
poly-typexpr::= typexpr  
  { ' ident }+ .  typexpr  
 
method-type::= method-name :  poly-typexpr

The table below shows the relative precedences and associativity of operators and non-closed type constructions. The constructions with higher precedences come first.

OperatorAssociativity
Type constructor application
*
->right
as

Type expressions denote types in definitions of data types as well as in type constraints over patterns and expressions.

Type variables

The type expression ' ident stands for the type variable named ident. The type expression _ stands for an anonymous type variable. In data type definitions, type variables are names for the data type parameters. In type constraints, they represent unspecified types that can be instantiated by any type to satisfy the type constraint. In general the scope of a named type variable is the whole enclosing definition; and they can only be generalized when leaving this scope. Anonymous variables have no such restriction. In the following cases, the scope of named type variables is restricted to the type expression where they appear: 1) for universal (explicitly polymorphic) type variables; 2) for type variables that only appear in public method specifications (as those variables will be made universal, as described in section 6.9.1); 3) for variables used as aliases, when the type they are aliased to would be invalid in the scope of the enclosing definition (i.e. when it contains free universal type variables, or locally defined types.)

Parenthesized types

The type expression ( typexpr ) denotes the same type as typexpr.

Function types

The type expression typexpr1 ->  typexpr2 denotes the type of functions mapping arguments of type typexpr1 to results of type typexpr2.

label-name :  typexpr1 ->  typexpr2 denotes the same function type, but the argument is labeled label.

? label-name :  typexpr1 ->  typexpr2 denotes the type of functions mapping an optional labeled argument of type typexpr1 to results of type typexpr2. That is, the physical type of the function will be typexpr1 option ->  typexpr2.

Tuple types

The type expression typexpr1 **  typexprn denotes the type of tuples whose elements belong to types typexpr1, …  typexprn respectively.

Constructed types

Type constructors with no parameter, as in typeconstr, are type expressions.

The type expression typexpr  typeconstr, where typeconstr is a type constructor with one parameter, denotes the application of the unary type constructor typeconstr to the type typexpr.

The type expression (typexpr1,…, typexprn)  typeconstr, where typeconstr is a type constructor with n parameters, denotes the application of the n-ary type constructor typeconstr to the types typexpr1 through typexprn.

Aliased and recursive types

The type expression typexpr as '  ident denotes the same type as typexpr, and also binds the type variable ident to type typexpr both in typexpr and in other types. In general the scope of an alias is the same as for a named type variable, and covers the whole enclosing definition. If the type variable ident actually occurs in typexpr, a recursive type is created. Recursive types for which there exists a recursive path that does not contain an object or variant type constructor are rejected, except when the -rectypes mode is selected.

If ' ident denotes an explicit polymorphic variable, and typexpr denotes either an object or variant type, the row variable of typexpr is captured by ' ident, and quantified upon.

Variant types

variant-type::= [ [ | ] tag-spec  { | tag-spec } ]  
  [> [ tag-spec ]  { | tag-spec } ]  
  [< [ | ] tag-spec-full  { | tag-spec-full }  [ > { `tag-name }+ ] ]  
 
tag-spec::= `tag-name  [ of typexpr ]  
  typexpr  
 
tag-spec-full::= `tag-name  [ of typexpr ]  { & typexpr }  
  typexpr  
 

Variant types describe the values a polymorphic variant may take.

The first case is an exact variant type: all possible tags are known, with their associated types, and they can all be present. Its structure is fully known.

The second case is an open variant type, describing a polymorphic variant value: it gives the list of all tags the value could take, with their associated types. This type is still compatible with a variant type containing more tags. A special case is the unknown type, which does not define any tag, and is compatible with any variant type.

The third case is a closed variant type. It gives information about all the possible tags and their associated types, and which tags are known to potentially appear in values. The above exact variant type is just an abbreviation for a closed variant type where all possible tags are also potentially present.

In all three cases, tags may be either specified directly in the `tag-name […] form, or indirectly through a type expression. In this last case, the type expression must expand to an exact variant type, whose tag specifications are inserted in its place.

Full specification of variant tags are only used for non-exact closed types. They can be understood as a conjunctive type for the argument: it is intended to have all the types enumerated in the specification.

Such conjunctive constraints may be unsatisfiable. In such a case the corresponding tag may not be used in a value of this type. This does not mean that the whole type is not valid: one can still use other available tags.

Object types

An object type < method-type  { ; method-type } > is a record of method types.

Each method may have an explicit polymorphic type: { ' ident }+ .  typexpr. Explicit polymorphic variables have a local scope, and an explicit polymorphic type can only be unified to an equivalent one, with polymorphic variables at the same positions.

The type < method-type  { ; method-type } ; .. > is the type of an object with methods and their associated types are described by method-type1, …,  method-typen, and possibly some other methods represented by the ellipsis. This ellipsis actually is a special kind of type variable (also called row variable in the literature) that stands for any number of extra method types.

#-types

The type # class-path is a special kind of abbreviation. This abbreviation unifies with the type of any object belonging to a subclass of class class-path. It is handled in a special way as it usually hides a type variable (an ellipsis, representing the methods that may be added in a subclass). In particular, it vanishes when the ellipsis gets instantiated. Each type expression # class-path defines a new type variable, so type # class-path -> #  class-path is usually not the same as type (# class-path as '  ident) -> '  ident.

Use of #-types to abbreviate variant types is deprecated. If t is an exact variant type then #t translates to [< t], and #t[> `tag1`tagk] translates to [< t > `tag1`tagk]

Variant and record types

There are no type expressions describing (defined) variant types nor record types, since those are always named, i.e. defined before use and referred to by name. Type definitions are described in section 6.8.1.

6.5  Constants

constant::= integer-literal  
  float-literal  
  char-literal  
  string-literal  
  constr  
  false  
  true  
  []  
  ()  
  `tag-name

The syntactic class of constants comprises literals from the four base types (integers, floating-point numbers, characters, character strings), and constant constructors from both normal and polymorphic variants, as well as the special constants false, true, [], and (), which behave like constant constructors.

6.6  Patterns

pattern::= value-name  
  _  
  constant  
  pattern as  value-name  
  ( pattern )  
  ( pattern :  typexpr )  
  pattern |  pattern  
  constr  pattern  
  `tag-name  pattern  
  #typeconstr-name  
  pattern  { , pattern }  
  { field =  pattern  { ; field =  pattern } }  
  [ pattern  { ; pattern } ]  
  pattern ::  pattern  
  [| pattern  { ; pattern } |]  
  lazy pattern

The table below shows the relative precedences and associativity of operators and non-closed pattern constructions. The constructions with higher precedences come first.

OperatorAssociativity
Constructor application
::right
,
|left
as

Patterns are templates that allow selecting data structures of a given shape, and binding identifiers to components of the data structure. This selection operation is called pattern matching; its outcome is either “this value does not match this pattern”, or “this value matches this pattern, resulting in the following bindings of names to values”.

Variable patterns

A pattern that consists in a value name matches any value, binding the name to the value. The pattern _ also matches any value, but does not bind any name.

Patterns are linear: a variable cannot appear several times in a given pattern. In particular, there is no way to test for equality between two parts of a data structure using only a pattern (but when guards can be used for this purpose).

Constant patterns

A pattern consisting in a constant matches the values that are equal to this constant.

Alias patterns

The pattern pattern1 as  value-name matches the same values as pattern1. If the matching against pattern1 is successful, the name name is bound to the matched value, in addition to the bindings performed by the matching against pattern1.

Parenthesized patterns

The pattern ( pattern1 ) matches the same values as pattern1. A type constraint can appear in a parenthesized pattern, as in ( pattern1 :  typexpr ). This constraint forces the type of pattern1 to be compatible with typexpr.

“Or” patterns

The pattern pattern1 |  pattern2 represents the logical “or” of the two patterns pattern1 and pattern2. A value matches pattern1 |  pattern2 either if it matches pattern1 or if it matches pattern2. The two sub-patterns pattern1 and pattern2 must bind exactly the same identifiers to values having the same types. Matching is performed from left to right. More precisely, in case some value v matches pattern1 |  pattern2, the bindings performed are those of pattern1 when v matches pattern1. Otherwise, value v matches pattern2 whose bindings are performed.

Variant patterns

The pattern constr  pattern1 matches all variants whose constructor is equal to constr, and whose argument matches pattern1.

The pattern pattern1 ::  pattern2 matches non-empty lists whose heads match pattern1, and whose tails match pattern2.

The pattern [ pattern1 ;;  patternn ] matches lists of length n whose elements match pattern1patternn, respectively. This pattern behaves like pattern1 ::::  patternn :: [].

Polymorphic variant patterns

The pattern `tag-name pattern1 matches all polymorphic variants whose tag is equal to tag-name, and whose argument matches pattern1.

Variant abbreviation patterns

If the type [('a,'b,...)] typeconstr = [`tag1  typexpr1 || `tagn  typexprn] is defined, then the pattern #typeconstr is a shorthand for the or-pattern (`tag1(_ : typexpr1) || `tagn(_ :  typexprn)). It matches all values of type #typeconstr.

Tuple patterns

The pattern pattern1 ,,  patternn matches n-tuples whose components match the patterns pattern1 through patternn. That is, the pattern matches the tuple values (v1, …, vn) such that patterni matches vi for i = 1,… , n.

Record patterns

The pattern { field1 =  pattern1 ;;  fieldn =  patternn } matches records that define at least the fields field1 through fieldn, and such that the value associated to fieldi matches the pattern patterni, for i = 1,… , n. The record value can define more fields than field1fieldn; the values associated to these extra fields are not taken into account for matching.

Array patterns

The pattern [| pattern1 ;;  patternn |] matches arrays of length n such that the i-th array element matches the pattern patterni, for i = 1,… , n.

6.7  Expressions

expr::= value-path  
  constant  
  ( expr )  
  begin expr end  
  ( expr :  typexpr )  
  expr ,  expr  { , expr }  
  constr  expr  
  `tag-name  expr  
  expr ::  expr  
  [ expr  { ; expr } ]  
  [| expr  { ; expr } |]  
  { field =  expr  { ; field =  expr } }  
  { expr with  field =  expr  { ; field =  expr } }  
  expr  { argument }+  
  prefix-symbol  expr  
  expr  infix-op  expr  
  expr .  field  
  expr .  field <-  expr  
  expr .(  expr )  
  expr .(  expr ) <-  expr  
  expr .[  expr ]  
  expr .[  expr ] <-  expr  
  if expr then  expr  [ else expr ]  
  while expr do  expr done  
  for ident =  expr  ( to ∣  downto ) expr do  expr done  
  expr ;  expr  
  match expr with  pattern-matching  
  function pattern-matching  
  fun multiple-matching  
  try expr with  pattern-matching  
  let [reclet-binding   { and let-binding } in  expr  
  new class-path  
  object class-body end  
  expr #  method-name  
  inst-var-name  
  inst-var-name <-  expr  
  ( expr :>  typexpr )  
  ( expr :  typexpr :>  typexpr )  
  {< inst-var-name =  expr  { ; inst-var-name =  expr } >}  
  assert expr  
  lazy expr  
 
argument::= expr  
  ~ label-name  
  ~ label-name :  expr  
  ? label-name  
  ? label-name :  expr  
 
pattern-matching::=| ] pattern  [when expr->  expr  { | pattern  [when expr->  expr }  
 
multiple-matching::=parameter }+  [when expr->  expr  
 
let-binding::= pattern =  expr  
  value-name  { parameter }  [: typexpr=  expr  
 
parameter::= pattern  
  ~ label-name  
  ~ ( label-name  [: typexpr)  
  ~ label-name :  pattern  
  ? label-name  
  ? ( label-name  [: typexpr]  [= expr)  
  ? label-name :  pattern  
  ? label-name : (  pattern  [: typexpr]  [= expr)

The table below shows the relative precedences and associativity of operators and non-closed constructions. The constructions with higher precedence come first. For infix and prefix symbols, we write “*…” to mean “any symbol starting with *”.

Construction or operatorAssociativity
prefix-symbol
. .( .[
function application, constructor application, assert, lazyleft
- -. (prefix)
** lsl lsr asrright
* / % mod land lor lxorleft
+ -left
::right
@ ^right
= < > | & $left
& &&right
or ||right
,
<- :=right
if
;right
let match fun function try

6.7.1  Basic expressions

Constants

Expressions consisting in a constant evaluate to this constant.

Value paths

Expressions consisting in an access path evaluate to the value bound to this path in the current evaluation environment. The path can be either a value name or an access path to a value component of a module.

Parenthesized expressions

The expressions ( expr ) and begin expr end have the same value as expr. Both constructs are semantically equivalent, but it is good style to use beginend inside control structures:

        if … then begin … ; … end else begin … ; … end

and () for the other grouping situations.

Parenthesized expressions can contain a type constraint, as in ( expr :  typexpr ). This constraint forces the type of expr to be compatible with typexpr.

Parenthesized expressions can also contain coercions ( expr  [: typexpr] :>  typexpr) (see subsection 6.7.6 below).

Function application

Function application is denoted by juxtaposition of (possibly labeled) expressions. The expression expr  argument1 …  argumentn evaluates the expression expr and those appearing in argument1 to argumentn. The expression expr must evaluate to a functional value f, which is then applied to the values of argument1, …,  argumentn.

The order in which the expressions expr,  argument1, …,  argumentn are evaluated is not specified.

Arguments and parameters are matched according to their respective labels. Argument order is irrelevant, except among arguments with the same label, or no label.

If a parameter is specified as optional (label prefixed by ?) in the type of expr, the corresponding argument will be automatically wrapped with the constructor Some, except if the argument itself is also prefixed by ?, in which case it is passed as is. If a non-labeled argument is passed, and its corresponding parameter is preceded by one or several optional parameters, then these parameters are defaulted, i.e. the value None will be passed for them. All other missing parameters (without corresponding argument), both optional and non-optional, will be kept, and the result of the function will still be a function of these missing parameters to the body of f.

As a special case, if the function has a known arity, all the arguments are unlabeled, and their number matches the number of non-optional parameters, then labels are ignored and non-optional parameters are matched in their definition order. Optional arguments are defaulted.

In all cases but exact match of order and labels, without optional parameters, the function type should be known at the application point. This can be ensured by adding a type constraint. Principality of the derivation can be checked in the -principal mode.

Function definition

Two syntactic forms are provided to define functions. The first form is introduced by the keyword function:

functionpattern1->expr1 
|… 
|patternn->exprn

This expression evaluates to a functional value with one argument. When this function is applied to a value v, this value is matched against each pattern pattern1 to patternn. If one of these matchings succeeds, that is, if the value v matches the pattern patterni for some i, then the expression expri associated to the selected pattern is evaluated, and its value becomes the value of the function application. The evaluation of expri takes place in an environment enriched by the bindings performed during the matching.

If several patterns match the argument v, the one that occurs first in the function definition is selected. If none of the patterns matches the argument, the exception Match_failure is raised.


The other form of function definition is introduced by the keyword fun:

fun parameter1 …  parametern ->  expr

This expression is equivalent to:

fun parameter1 ->fun  parametern ->  expr

The parameter patterns ~var and ~(var [: typexpr]) are shorthands for respectively ~var:var and ~var:(var [: typexpr]), and similarly for their optional counterparts.

Functions of the form fun ?lab:( pattern =  expr0 ) ->  expr are equivalent to

fun ?lab:ident -> let  pattern = match  ident with Some  ident ->  ident | None ->  expr0 in  expr

where ident is a fresh variable. When expr0 will be evaluated is left unspecified.

After these two transformations, expressions are of the form

fun [label1]  pattern1 ->fun  [labeln]  patternn ->  expr

If we ignore labels, which will only be meaningful at function application, this is equivalent to

function pattern1 ->function  patternn ->  expr

That is, the fun expression above evaluates to a curried function with n arguments: after applying this function n times to the values v1 … vm, the values will be matched in parallel against the patterns pattern1 …  patternn. If the matching succeeds, the function returns the value of expr in an environment enriched by the bindings performed during the matchings. If the matching fails, the exception Match_failure is raised.

Guards in pattern-matchings

Cases of a pattern matching (in the function, fun, match and try constructs) can include guard expressions, which are arbitrary boolean expressions that must evaluate to true for the match case to be selected. Guards occur just before the -> token and are introduced by the when keyword:

functionpattern1   [when   cond1]->expr1 
|… 
|patternn    [when   condn]->exprn

Matching proceeds as described before, except that if the value matches some pattern patterni which has a guard condi, then the expression condi is evaluated (in an environment enriched by the bindings performed during matching). If condi evaluates to true, then expri is evaluated and its value returned as the result of the matching, as usual. But if condi evaluates to false, the matching is resumed against the patterns following patterni.

Local definitions

The let and let rec constructs bind value names locally. The construct

let pattern1 =  expr1 andand  patternn =  exprn in  expr

evaluates expr1 …  exprn in some unspecified order, then matches their values against the patterns pattern1 …  patternn. If the matchings succeed, expr is evaluated in the environment enriched by the bindings performed during matching, and the value of expr is returned as the value of the whole let expression. If one of the matchings fails, the exception Match_failure is raised.

An alternate syntax is provided to bind variables to functional values: instead of writing

let ident = fun  parameter1 …  parameterm ->  expr

in a let expression, one may instead write

let ident  parameter1 …  parameterm =  expr


Recursive definitions of names are introduced by let rec:

let rec pattern1 =  expr1 andand  patternn =  exprn in  expr

The only difference with the let construct described above is that the bindings of names to values performed by the pattern-matching are considered already performed when the expressions expr1 to exprn are evaluated. That is, the expressions expr1 to exprn can reference identifiers that are bound by one of the patterns pattern1, …,  patternn, and expect them to have the same value as in expr, the body of the let rec construct.

The recursive definition is guaranteed to behave as described above if the expressions expr1 to exprn are function definitions (fun … or function …), and the patterns pattern1 …  patternn are just value names, as in:

let rec name1 = funandand  namen = funin  expr

This defines name1 …  namen as mutually recursive functions local to expr.

The behavior of other forms of let rec definitions is implementation-dependent. The current implementation also supports a certain class of recursive definitions of non-functional values, as explained in section 7.3.

6.7.2  Control structures

Sequence

The expression expr1 ;  expr2 evaluates expr1 first, then expr2, and returns the value of expr2.

Conditional

The expression if expr1 then  expr2 else  expr3 evaluates to the value of expr2 if expr1 evaluates to the boolean true, and to the value of expr3 if expr1 evaluates to the boolean false.

The else expr3 part can be omitted, in which case it defaults to else ().

Case expression

The expression

matchexpr 
withpattern1->expr1 
|… 
|patternn->exprn

matches the value of expr against the patterns pattern1 to patternn. If the matching against patterni succeeds, the associated expression expri is evaluated, and its value becomes the value of the whole match expression. The evaluation of expri takes place in an environment enriched by the bindings performed during matching. If several patterns match the value of expr, the one that occurs first in the match expression is selected. If none of the patterns match the value of expr, the exception Match_failure is raised.

Boolean operators

The expression expr1 &&  expr2 evaluates to true if both expr1 and expr2 evaluate to true; otherwise, it evaluates to false. The first component, expr1, is evaluated first. The second component, expr2, is not evaluated if the first component evaluates to false. Hence, the expression expr1 &&  expr2 behaves exactly as

if expr1 then  expr2 else false.

The expression expr1 ||  expr2 evaluates to true if one of expr1 and expr2 evaluates to true; otherwise, it evaluates to false. The first component, expr1, is evaluated first. The second component, expr2, is not evaluated if the first component evaluates to true. Hence, the expression expr1 ||  expr2 behaves exactly as

if expr1 then true else  expr2.

The boolean operator & is synonymous for &&. The boolean operator or is synonymous for ||.

Loops

The expression while expr1 do  expr2 done repeatedly evaluates expr2 while expr1 evaluates to true. The loop condition expr1 is evaluated and tested at the beginning of each iteration. The whole whiledone expression evaluates to the unit value ().

The expression for name =  expr1 to  expr2 do  expr3 done first evaluates the expressions expr1 and expr2 (the boundaries) into integer values n and p. Then, the loop body expr3 is repeatedly evaluated in an environment where name is successively bound to the values n, n+1, …, p−1, p. The loop body is never evaluated if n > p.

The expression for name =  expr1 downto  expr2 do  expr3 done evaluates similarly, except that name is successively bound to the values n, n−1, …, p+1, p. The loop body is never evaluated if n < p.

In both cases, the whole for expression evaluates to the unit value ().

Exception handling

The expression

try expr 
withpattern1->expr1 
|… 
|patternn->exprn

evaluates the expression expr and returns its value if the evaluation of expr does not raise any exception. If the evaluation of expr raises an exception, the exception value is matched against the patterns pattern1 to patternn. If the matching against patterni succeeds, the associated expression expri is evaluated, and its value becomes the value of the whole try expression. The evaluation of expri takes place in an environment enriched by the bindings performed during matching. If several patterns match the value of expr, the one that occurs first in the try expression is selected. If none of the patterns matches the value of expr, the exception value is raised again, thereby transparently “passing through” the try construct.

6.7.3  Operations on data structures

Products

The expression expr1 ,,  exprn evaluates to the n-tuple of the values of expressions expr1 to exprn. The evaluation order for the subexpressions is not specified.

Variants

The expression constr  expr evaluates to the variant value whose constructor is constr, and whose argument is the value of expr.

For lists, some syntactic sugar is provided. The expression expr1 ::  expr2 stands for the constructor ( :: ) applied to the argument ( expr1 ,  expr2 ), and therefore evaluates to the list whose head is the value of expr1 and whose tail is the value of expr2. The expression [ expr1 ;;  exprn ] is equivalent to expr1 ::::  exprn :: [], and therefore evaluates to the list whose elements are the values of expr1 to exprn.

Polymorphic variants

The expression `tag-name  expr evaluates to the variant value whose tag is tag-name, and whose argument is the value of expr.

Records

The expression { field1 =  expr1 ;;  fieldn =  exprn } evaluates to the record value { field1 = v1; …; fieldn = vn } where vi is the value of expri for i = 1,… , n. The fields field1 to fieldn must all belong to the same record types; all fields belonging to this record type must appear exactly once in the record expression, though they can appear in any order. The order in which expr1 to exprn are evaluated is not specified.

The expression { expr with  field1 =  expr1 ;;  fieldn =  exprn } builds a fresh record with fields field1 …  fieldn equal to expr1 …  exprn, and all other fields having the same value as in the record expr. In other terms, it returns a shallow copy of the record expr, except for the fields field1 …  fieldn, which are initialized to expr1 …  exprn.

The expression expr1 .  field evaluates expr1 to a record value, and returns the value associated to field in this record value.

The expression expr1 .  field <-  expr2 evaluates expr1 to a record value, which is then modified in-place by replacing the value associated to field in this record by the value of expr2. This operation is permitted only if field has been declared mutable in the definition of the record type. The whole expression expr1 .  field <-  expr2 evaluates to the unit value ().

Arrays

The expression [| expr1 ;;  exprn |] evaluates to a n-element array, whose elements are initialized with the values of expr1 to exprn respectively. The order in which these expressions are evaluated is unspecified.

The expression expr1 .(  expr2 ) returns the value of element number expr2 in the array denoted by expr1. The first element has number 0; the last element has number n−1, where n is the size of the array. The exception Invalid_argument is raised if the access is out of bounds.

The expression expr1 .(  expr2 ) <-  expr3 modifies in-place the array denoted by expr1, replacing element number expr2 by the value of expr3. The exception Invalid_argument is raised if the access is out of bounds. The value of the whole expression is ().

Strings

The expression expr1 .[  expr2 ] returns the value of character number expr2 in the string denoted by expr1. The first character has number 0; the last character has number n−1, where n is the length of the string. The exception Invalid_argument is raised if the access is out of bounds.

The expression expr1 .[  expr2 ] <-  expr3 modifies in-place the string denoted by expr1, replacing character number expr2 by the value of expr3. The exception Invalid_argument is raised if the access is out of bounds. The value of the whole expression is ().

6.7.4  Operators

Symbols from the class infix-symbols, as well as the keywords *, =, or and &, can appear in infix position (between two expressions). Symbols from the class prefix-symbols can appear in prefix position (in front of an expression).

Infix and prefix symbols do not have a fixed meaning: they are simply interpreted as applications of functions bound to the names corresponding to the symbols. The expression prefix-symbol  expr is interpreted as the application ( prefix-symbol )  expr. Similarly, the expression expr1  infix-symbol  expr2 is interpreted as the application ( infix-symbol )  expr1  expr2.

The table below lists the symbols defined in the initial environment and their initial meaning. (See the description of the standard library module Pervasive in chapter 20 for more details). Their meaning may be changed at any time using let ( infix-op )  name1  name2 =

OperatorInitial meaning
+Integer addition.
- (infix)Integer subtraction.
- (prefix)Integer negation.
*Integer multiplication.
/Integer division. Raise Division_by_zero if second argument is zero.
modInteger modulus. Raise Division_by_zero if second argument is zero.
landBitwise logical “and” on integers.
lorBitwise logical “or” on integers.
lxorBitwise logical “exclusive or” on integers.
lslBitwise logical shift left on integers.
lsrBitwise logical shift right on integers.
asrBitwise arithmetic shift right on integers.
+.Floating-point addition.
-. (infix)Floating-point subtraction.
-. (prefix)Floating-point negation.
*.Floating-point multiplication.
/.Floating-point division.
**Floating-point exponentiation.
@ List concatenation.
^ String concatenation.
! Dereferencing (return the current contents of a reference).
:=Reference assignment (update the reference given as first argument with the value of the second argument).
= Structural equality test.
<> Structural inequality test.
== Physical equality test.
!= Physical inequality test.
< Test “less than”.
<= Test “less than or equal”.
> Test “greater than”.
>= Test “greater than or equal”.

6.7.5  Objects

Object creation

When class-path evaluates to a class body, new class-path evaluates to an object containing the instance variables and methods of this class.

When class-path evaluates to a class function, new class-path evaluates to a function expecting the same number of arguments and returning a new object of this class.

Immediate object creation

Creating directly an object through the object class-body end construct is operationally equivalent to defining locally a class class-name = object  class-body end —see sections 6.9.2 and following for the syntax of class-body— and immediately creating a single object from it by new class-name.

The typing of immediate objects is slightly different from explicitely defining a class in two respects. First, the inferred object type may contain free type variables. Second, since the class body of an immediate object will never be extended, its self type can be unified with a closed object type.

Message sending

The expression expr #  method-name invokes the method method-name of the object denoted by expr.

If method-name is a polymorphic method, its type should be known at the invocation site. This is true for instance if expr is the name of a fresh object (let ident = new  class-path … ) or if there is a type constraint. Principality of the derivation can be checked in the -principal mode.

Accessing and modifying instance variables

The instance variables of a class are visible only in the body of the methods defined in the same class or a class that inherits from the class defining the instance variables. The expression inst-var-name evaluates to the value of the given instance variable. The expression inst-var-name <-  expr assigns the value of expr to the instance variable inst-var-name, which must be mutable. The whole expression inst-var-name <-  expr evaluates to ().

Object duplication

An object can be duplicated using the library function Oo.copy (see Module Oo). Inside a method, the expression {< inst-var-name =  expr  { ; inst-var-name =  expr } >} returns a copy of self with the given instance variables replaced by the values of the associated expressions; other instance variables have the same value in the returned object as in self.

6.7.6  Coercions

Expressions whose type contains object or polymorphic variant types can be explicitly coerced (weakened) to a supertype. The expression (expr :>  typexpr) coerces the expression expr to type typexpr. The expression (expr :  typexpr1 :>  typexpr2) coerces the expression expr from type typexpr1 to type typexpr2.

The former operator will sometimes fail to coerce an expression expr from a type t1 to a type t2 even if type t1 is a subtype of type t2: in the current implementation it only expands two levels of type abbreviations containing objects and/or variants, keeping only recursion when it is explicit in the class type (for objects). As an exception to the above algorithm, if both the inferred type of expr and typexpr are ground (i.e. do not contain type variables), the former operator behaves as the latter one, taking the inferred type of expr as typexpr1. In case of failure with the former operator, the latter one should be used.

It is only possible to coerce an expression expr from type typexpr1 to type typexpr2, if the type of expr is an instance of typexpr1 (like for a type annotation), and typexpr1 is a subtype of typexpr2. The type of the coerced expression is an instance of typexpr2. If the types contain variables, they may be instanciated by the subtyping algorithm, but this is only done after determining whether typexpr1 is a potential subtype of typexpr2. This means that typing may fail during this latter unification step, even if some instance of typexpr1 is a subtype of some instance of typexpr2. In the following paragraphs we describe the subtyping relation used.

Object types

A fixed object type admits as subtype any object type including all its methods. The types of the methods shall be subtypes of those in the supertype. Namely,

 <  met1   :  typ1   ;  ...   ;  metn   :  typn  >  

is a supertype of

 <  met1   :  typ'1   ;  ...   ;  metn   :  typ'n   ;  metn+1   :  typ'n+1   ;  ...   ;  metn+m   :  typ'n+m  [ ; ..  > 

which may contain an ellipsis .., if every typi is a supertype of typ'i.

A monomorphic method type can be a supertype of a polymorphic method type. Namely, if typ is an instance of typ', then 'a1 ... 'an .typ' is a subtype of typ.

Inside a class definition, newly defined types are not available for subtyping, as the type abbreviations are not yet completely defined. There is an exception for coercing self to the (exact) type of its class: this is allowed if the type of self does not appear in a contravariant position in the class type, i.e. if there are no binary methods.

Polymorphic variant types

A polymorphic variant type typ is subtype of another polymorphic variant type typ' if the upper bound of typ (i.e. the maximum set of constructors that may appear in an instance of typ) is included in the lower bound of typ', and the types of arguments for the constructors of typ are subtypes of those in typ'. Namely,

 [[ <  'C1   of  typ1   |  ...   | 'Cn   of  typn   ] 

which may be a shrinkable type, is a subtype of

 [[ >  'C1   of  typ'1   |  ...   | 'Cn   of  typ'n  | 'Cn+1   of  typ'n+1   |  ...   | 'Cn+m   of  typ'n+m   ] 

which may be an extensible type, if every typi is a subtype of typ'i.

Variance

Other types do not introduce new subtyping, but they may propagate the subtyping of their arguments. For instance, typ1 * typ2 is a subtype of typ'1 * typ'2 when typ1 and typ2 are respectively subtypes of typ'1 and typ'2. For function types, the relation is more subtle: typ1 -> typ2 is a subtype of typ'1 -> typ'2 if typ1 is a supertype of typ'1 and typ2 is a subtype of typ'2. For this reason, function types are covariant in their second argument (like tuples), but contravariant in their first argument. Mutable types, like array or ref are neither covariant nor contravariant, they are nonvariant, that is they do not propagate subtyping.

For user defined types, the variance is automatically inferred: a parameter is covariant if it has only covariant occurences, contravariant if it has only contravariant occurences, variance-free if it has no occurences, and nonvariant otherwise. A variance-free parameter may change freely through subtyping, it does not have to be a subtype or a supertype. For abstract and private types, the variance must be given explicitly, otherwise the default is nonvariant. This is also the case for constrained arguments in type definitions.

6.8  Type and exception definitions

6.8.1  Type definitions

Type definitions bind type constructors to data types: either variant types, record types, type abbreviations, or abstract data types. They also bind the value constructors and record fields associated with the definition.

type-definition::= type typedef  { and typedef }  
 
typedef::= [type-params]  typeconstr-name  [type-information]  
 
type-information::= [type-equation]  [type-representation]  { type-constraint }  
 
type-equation::= = typexpr  
 
type-representation::= = constr-decl  { | constr-decl }  
  = { field-decl  { ; field-decl } }  
 
type-params::= type-param  
  ( type-param  { , type-param } )  
 
type-param::= ' ident  
  + ' ident  
  - ' ident  
 
constr-decl::= constr-name  
  constr-name of  typexpr  { * typexpr }  
 
field-decl::= field-name :  poly-typexpr  
  mutable field-name :  poly-typexpr  
 
type-constraint::= constraint ' ident =  typexpr  
 

Type definitions are introduced by the type keyword, and consist in one or several simple definitions, possibly mutually recursive, separated by the and keyword. Each simple definition defines one type constructor.

A simple definition consists in a lowercase identifier, possibly preceded by one or several type parameters, and followed by an optional type equation, then an optional type representation, and then a constraint clause. The identifier is the name of the type constructor being defined.

The optional type parameters are either one type variable ' ident, for type constructors with one parameter, or a list of type variables ('ident1,…,' identn), for type constructors with several parameters. Each type parameter may be prefixed by a variance constraint + (resp. -) indicating that the parameter is covariant (resp. contravariant). These type parameters can appear in the type expressions of the right-hand side of the definition, restricted eventually by a variance constraint ; i.e. a covariant parameter may only appear on the right side of a functional arrow (more precisely, follow the left branch of an even number of arrows), and a contravariant parameter only the left side (left branch of an odd number of arrows). If the type has either a representation or an equation, and the parameter is free (i.e. not bound via a type constraint to a constructed type), its variance constraint is checked but subtyping etc. will use the inferred variance of the parameter, which may be better; otherwise (i.e. for abstract types or non-free parameters), the variance must be given explicitly, and the parameter is invariant if no variance was given.

The optional type equation = typexpr makes the defined type equivalent to the type expression typexpr on the right of the = sign: one can be substituted for the other during typing. If no type equation is given, a new type is generated: the defined type is incompatible with any other type.

The optional type representation describes the data structure representing the defined type, by giving the list of associated constructors (if it is a variant type) or associated fields (if it is a record type). If no type representation is given, nothing is assumed on the structure of the type besides what is stated in the optional type equation.

The type representation = constr-decl  { | constr-decl } describes a variant type. The constructor declarations constr-decl1, …,  constr-decln describe the constructors associated to this variant type. The constructor declaration constr-name of  typexpr1, …,  typexprn declares the name constr-name as a non-constant constructor, whose arguments have types typexpr1typexprn. The constructor declaration constr-name declares the name constr-name as a constant constructor. Constructor names must be capitalized.

The type representation = { field-decl  { ; field-decl } } describes a record type. The field declarations field-decl1, …,  field-decln describe the fields associated to this record type. The field declaration field-name :  poly-typexpr declares field-name as a field whose argument has type poly-typexpr. The field declaration mutable field-name :  poly-typexpr behaves similarly; in addition, it allows physical modification over the argument to this field. Immutable fields are covariant, but mutable fields are neither covariant nor contravariant. Both mutable and immutable field may have an explicitly polymorphic type. The polymorphism of the contents is statically checked whenever a record value is created or modified. Extracted values may have their types instanciated.

The two components of a type definition, the optional equation and the optional representation, can be combined independently, giving rise to four typical situations:

Abstract type: no equation, no representation.
 
When appearing in a module signature, this definition specifies nothing on the type constructor, besides its number of parameters: its representation is hidden and it is assumed incompatible with any other type.
Type abbreviation: an equation, no representation.
 
This defines the type constructor as an abbreviation for the type expression on the right of the = sign.
New variant type or record type: no equation, a representation.
 
This generates a new type constructor and defines associated constructors or fields, through which values of that type can be directly built or inspected.
Re-exported variant type or record type: an equation, a representation.
 
In this case, the type constructor is defined as an abbreviation for the type expression given in the equation, but in addition the constructors or fields given in the representation remain attached to the defined type constructor. The type expression in the equation part must agree with the representation: it must be of the same kind (record or variant) and have exactly the same constructors or fields, in the same order, with the same arguments.

The type variables appearing as type parameters can optionally be prefixed by + or - to indicate that the type constructor is covariant or contravariant with respect to this parameter. This variance information is used to decide subtyping relations when checking the validity of :> coercions (see section 6.7.5).

For instance, type +'a t declares t as an abstract type that is covariant in its parameter; this means that if the type τ is a subtype of the type σ, then τ t is a subtype of σ t. Similarly, type -'a t declares that the abstract type t is contravariant in its parameter: if τ is subtype of σ, then σ t is subtype of τ t. If no + or - variance annotation is given, the type constructor is assumed invariant in the corresponding parameter. For instance, the abstract type declaration type 'a t means that τ t is neither a subtype nor a supertype of σ t if τ is subtype of σ.

The variance indicated by the + and - annotations on parameters are required only for abstract types. For abbreviations, variant types or record types, the variance properties of the type constructor are inferred from its definition, and the variance annotations are only checked for conformance with the definition.

The construct constraint ' ident =  typexpr allows to specify type parameters. Any actual type argument corresponding to the type parameter ident has to be an instance of typexpr (more precisely, ident and typexpr are unified). Type variables of typexpr can appear in the type equation and the type declaration.

6.8.2  Exception definitions

exception-definition::= exception constr-name  [of typexpr  { * typexpr }]  
  exception constr-name =  constr

Exception definitions add new constructors to the built-in variant type exn of exception values. The constructors are declared as for a definition of a variant type.

The form exception constr-name  [of typexpr  { * typexpr }] generates a new exception, distinct from all other exceptions in the system. The form exception constr-name =  constr gives an alternate name to an existing exception.

6.9  Classes

Classes are defined using a small language, similar to the module language.

6.9.1  Class types

Class types are the class-level equivalent of type expressions: they specify the general shape and type properties of classes.

class-type::= class-body-type  
   [[?]label-name:]  typexpr ->  class-type  
 
class-body-type::= object [( typexpr )]  {class-field-specend  
   class-path  
   [ typexpr  {, typexpr]  class-path  
 
class-field-spec::= inherit class-type  
   val [mutable] [virtualinst-var-name :  typexpr  
   method [privatemethod-name :  poly-typexpr  
   method [privatevirtual method-name :  poly-typexpr  
   constraint typexpr =  typexpr  
 

Simple class expressions

The expression class-path is equivalent to the class type bound to the name class-path. Similarly, the expression [ typexpr1 , …  typexprn ]  class-path is equivalent to the parametric class type bound to the name class-path, in which type parameters have been instanciated to respectively typexpr1, …typexprn.

Class function type

The class type expression typexpr ->  class-type is the type of class functions (functions from values to classes) that take as argument a value of type typexpr and return as result a class of type class-type.

Class body type

The class type expression object [( typexpr )]  {class-field-spec} end is the type of a class body. It specifies its instance variables and methods. In this type, typexpr is matched against the self type, therefore providing a binding for the self type.

A class body will match a class body type if it provides definitions for all the components specified in the class type, and these definitions meet the type requirements given in the class type. Furthermore, all methods either virtual or public present in the class body must also be present in the class type (on the other hand, some instance variables and concrete private methods may be omitted). A virtual method will match a concrete method, which makes it possible to forget its implementation. An immutable instance variable will match a mutable instance variable.

Inheritance

The inheritance construct inherit class-type allows to include methods and instance variables from other classes types. The instance variable and method types from this class type are added into the current class type.

Instance variable specification

A specification of an instance variable is written val [mutable] [virtual] inst-var-name :  typexpr, where inst-var-name is the name of the instance variable and typexpr its expected type. The flag mutable indicates whether this instance variable can be physically modified. The flag virtual indicates that this instance variable is not initialized. It can be initialized later through inheritance.

An instance variable specification will hide any previous specification of an instance variable of the same name.

Method specification

The specification of a method is written method [private] method-name :  poly-typexpr, where method-name is the name of the method and poly-typexpr its expected type, possibly polymorphic. The flag private indicates that the method cannot be accessed from outside the object.

The polymorphism may be left implicit in public method specifications: any type variable which is not bound to a class parameter and does not appear elsewhere inside the class specification will be assumed to be universal, and made polymorphic in the resulting method type. Writing an explicit polymorphic type will disable this behaviour.

Several specification for the same method must have compatible types. Any non-private specification of a method forces it to be public.

Virtual method specification

Virtual method specification is written method [private] virtual method-name :  poly-typexpr, where method-name is the name of the method and poly-typexpr its expected type.

Constraints on type parameters

The construct constraint typexpr1 =  typexpr2 forces the two type expressions to be equals. This is typically used to specify type parameters: they can be that way be bound to a specified type expression.

6.9.2  Class expressions

Class expressions are the class-level equivalent of value expressions: they evaluate to classes, thus providing implementations for the specifications expressed in class types.

class-expr::= class-path  
   [ typexpr  {, typexpr]  class-path  
   ( class-expr )  
   ( class-expr :  class-type )  
   class-expr  {argument}+  
   fun {parameter}+ ->  class-expr  
   let [reclet-binding  {and let-bindingin  class-expr  
   object [( pattern  [: typexpr)]  { class-field } end  
 
class-field::= inherit class-expr  [as value-name]  
   val [mutableinst-var-name  [: typexpr=  expr  
   val [mutablevirtual inst-var-name :  typexpr  
   method [privatemethod-name  {parameter}  [: typexpr=  expr  
   method [privatemethod-name :  poly-typexpr =  expr  
   method [privatevirtual method-name :  poly-typexpr  
   constraint typexpr =  typexpr  
   initializer expr  
 

Simple class expressions

The expression class-path evaluates to the class bound to the name class-path. Similarly, the expression [ typexpr1 , …  typexprn ]  class-path evaluates to the parametric class bound to the name class-path, in which type parameters have been instanciated to respectively typexpr1, …typexprn.

The expression ( class-expr ) evaluates to the same module as class-expr.

The expression ( class-expr :  class-type ) checks that class-type match the type of class-expr (that is, that the implementation class-expr meets the type specification class-type). The whole expression evaluates to the same class as class-expr, except that all components not specified in class-type are hidden and can no longer be accessed.

Class application

Class application is denoted by juxtaposition of (possibly labeled) expressions. Evaluation works as for expression application.

Class function

The expression fun [[?]label-name:pattern ->  class-expr evaluates to a function from values to classes. When this function is applied to a value v, this value is matched against the pattern pattern and the result is the result of the evaluation of class-expr in the extended environment.

Conversion from functions with default values to functions with patterns only works identically for class functions as for normal functions.

The expression

fun parameter1 …  parametern ->  class-expr

is a short form for

fun parameter1 ->fun  parametern ->  expr

Local definitions

The let and let rec constructs bind value names locally, as for the core language expressions.

Class body

class-body::=  [( pattern  [: typexpr)]  { class-field }

The expression object class-body end denotes a class body. This is the prototype for an object : it lists the instance variables and methods of an objet of this class.

A class body is a class value: it is not evaluated at once. Rather, its components are evaluated each time an object is created.

In a class body, the pattern ( pattern  [: typexpr] ) is matched against self, therefore provinding a binding for self and self type. Self can only be used in method and initializers.

Self type cannot be a closed object type, so that the class remains extensible.

Inheritance

The inheritance construct inherit class-expr allows to reuse methods and instance variables from other classes. The class expression class-expr must evaluate to a class body. The instance variables, methods and initializers from this class body are added into the current class. The addition of a method will override any previously defined methods of the same name.

An ancestor can be bound by prepending the construct as value-name to the inheritance construct above. value-name is not a true variable and can only be used to select a method, i.e. in an expression value-name #  method-name. This gives access to the method method-name as it was defined in the parent class even if it is redefined in the current class. The scope of an ancestor binding is limited to the current class. The ancestor method may be called from a subclass but only indirectly.

Instance variable definition

The definition val [mutable] inst-var-name =  expr adds an instance variable inst-var-name whose initial value is the value of expression expr. The flag mutable allows physical modification of this variable by methods.

An instance variables can only be used in the following methods and initializers of the class.

Since version 3.10, redefinitions of a visible instance variable with the same name do not create a new variable, but are merged, using the last value for initialization. They must have identical types and mutability. However, if an instance variable is hidden by omitting it from an interface, it will be kept distinct from other instance variables with the same name.

Virtual instance variable definition

Variable specification is written val [mutable] virtual inst-var-name :  typexpr. It specifies whether the variable is modifiable, and gives its type.

Virtual instance variables were added in version 3.10.

Method definition

Method definition is written method method-name =  expr. The definition of a method overrides any previous definition of this method. The method will be public (that is, not private) if any of the definition states so.

A private method, method private method-name =  expr, is a method that can only be invoked on self (from other methods of the same object, defined in this class or one of its subclasses). This invocation is performed using the expression value-name #  method-name, where value-name is directly bound to self at the beginning of the class definition. Private methods do not appear in object types. A method may have both public and private definitions, but as soon as there is a public one, all subsequent definitions will be made public.

Methods may have an explicitly polymorphic type, allowing them to be used polymorphically in programs (even for the same object). The explicit declaration may be done in one of three ways: (1) by giving an explicit polymorphic type in the method definition, immediately after the method name, i.e. method [private] method-name :  {' ident}+ .  typexpr =  expr; (2) by a forward declaration of the explicit polymorphic type through a virtual method definition; (3) by importing such a declaration through inheritance and/or constraining the type of self.

Some special expressions are available in method bodies for manipulating instance variables and duplicating self:

expr::= …  
  inst-var-name <-  expr  
  {< [ inst-var-name =  expr  { ; inst-var-name =  expr } ] >}  
 

The expression inst-var-name <-  expr modifies in-place the current object by replacing the value associated to inst-var-name by the value of expr. Of course, this instance variable must have been declared mutable.

The expression {< [ inst-var-name =  expr  { ; inst-var-name =  expr } ] >} evaluates to a copy of the current object in which the values of instance variables inst-var-name1, …,  inst-var-namen have been replaced by the values of the corresponding expressions expr1, …,  exprn.

Virtual method definition

Method specification is written method [private] virtual method-name :  poly-typexpr. It specifies whether the method is public or private, and gives its type. If the method is intended to be polymorphic, the type should be explicit.

Constraints on type parameters

The construct constraint typexpr1 =  typexpr2 forces the two type expressions to be equals. This is typically used to specify type parameters: they can be that way be bound to a specified type expression.

Initializers

A class initializer initializer expr specifies an expression that will be evaluated when an object will be created from the class, once all the instance variables have been initialized.

6.9.3  Class definitions

class-definition::= class class-binding  { and class-binding }  
 
class-binding::= [virtual] [[ type-parameters ]]  class-name  {parameter}  [: class-type]  =  class-expr  
 
type-parameters::= ' ident  { , ' ident }  
 

A class definition class class-binding  { and class-binding } is recursive. Each class-binding defines a class-name that can be used in the whole expression except for inheritance. It can also be used for inheritance, but only in the definitions that follow its own.

A class binding binds the class name class-name to the value of expression class-expr. It also binds the class type class-name to the type of the class, and defines two type abbreviations : class-name and # class-name. The first one is the type of objects of this class, while the second is more general as it unifies with the type of any object belonging to a subclass (see section 6.4).

Virtual class

A class must be flagged virtual if one of its methods is virtual (that is, appears in the class type, but is not actually defined). Objects cannot be created from a virtual class.

Type parameters

The class type parameters correspond to the ones of the class type and of the two type abbreviations defined by the class binding. They must be bound to actual types in the class definition using type constraints. So that the abbreviations are well-formed, type variables of the inferred type of the class must either be type parameters or be bound in the constraint clause.

6.9.4  Class specification

class-specification::= class class-spec  { and class-spec }  
 
class-spec::= [virtual] [[ type-parameters ]]  class-name :  class-type  
 

This is the counterpart in signatures of class definitions. A class specification matches a class definition if they have the same type parameters and their types match.

6.9.5  Class type definitions

classtype-definition::= class type classtype-def  { and classtype-def }  
 
classtype-def::= [virtual] [[ type-parameters ]]  class-name =  class-body-type  
 

A class type definition class class-name =  class-body-type defines an abbreviation class-name for the class body type class-body-type. As for class definitions, two type abbreviations class-name and # class-name are also defined. The definition can be parameterized by some type parameters. If any method in the class type body is virtual, the definition must be flagged virtual.

Two class type definitions match if they have the same type parameters and the types they expand to match.

6.10  Module types (module specifications)

Module types are the module-level equivalent of type expressions: they specify the general shape and type properties of modules.

module-type::= modtype-path  
  sig { specification  [;;] } end  
  functor ( module-name :  module-type ) ->  module-type  
  module-type with  mod-constraint  { and mod-constraint }  
  ( module-type )  
 
mod-constraint::= type [type-parameters]  typeconstr =  typexpr  
  module module-path =  extended-module-path  
 
specification::= val value-name :  typexpr  
  external value-name :  typexpr =  external-declaration  
  type-definition  
  exception constr-decl  
  class-specification  
  classtype-definition  
  module module-name :  module-type  
  module module-name  { ( module-name :  module-type ) } :  module-type  
  module type modtype-name  
  module type modtype-name =  module-type  
  open module-path  
  include module-type  
 

6.10.1  Simple module types

The expression modtype-path is equivalent to the module type bound to the name modtype-path. The expression ( module-type ) denotes the same type as module-type.

6.10.2  Signatures

Signatures are type specifications for structures. Signatures sigend are collections of type specifications for value names, type names, exceptions, module names and module type names. A structure will match a signature if the structure provides definitions (implementations) for all the names specified in the signature (and possibly more), and these definitions meet the type requirements given in the signature.

For compatibility with Caml Light, an optional ;; is allowed after each specification in a signature. The ;; has no semantic meaning.

Value specifications

A specification of a value component in a signature is written val value-name :  typexpr, where value-name is the name of the value and typexpr its expected type.

The form external value-name :  typexpr =  external-declaration is similar, except that it requires in addition the name to be implemented as the external function specified in external-declaration (see chapter 18).

Type specifications

A specification of one or several type components in a signature is written type typedef  { and typedef } and consists of a sequence of mutually recursive definitions of type names.

Each type definition in the signature specifies an optional type equation = typexpr and an optional type representation = constr-decl … or = { field-decl}. The implementation of the type name in a matching structure must be compatible with the type expression specified in the equation (if given), and have the specified representation (if given). Conversely, users of that signature will be able to rely on the type equation or type representation, if given. More precisely, we have the following four situations:

Abstract type: no equation, no representation.
 
Names that are defined as abstract types in a signature can be implemented in a matching structure by any kind of type definition (provided it has the same number of type parameters). The exact implementation of the type will be hidden to the users of the structure. In particular, if the type is implemented as a variant type or record type, the associated constructors and fields will not be accessible to the users; if the type is implemented as an abbreviation, the type equality between the type name and the right-hand side of the abbreviation will be hidden from the users of the structure. Users of the structure consider that type as incompatible with any other type: a fresh type has been generated.
Type abbreviation: an equation = typexpr, no representation.
 
The type name must be implemented by a type compatible with typexpr. All users of the structure know that the type name is compatible with typexpr.
New variant type or record type: no equation, a representation.
 
The type name must be implemented by a variant type or record type with exactly the constructors or fields specified. All users of the structure have access to the constructors or fields, and can use them to create or inspect values of that type. However, users of the structure consider that type as incompatible with any other type: a fresh type has been generated.
Re-exported variant type or record type: an equation, a representation.
 
This case combines the previous two: the representation of the type is made visible to all users, and no fresh type is generated.

Exception specification

The specification exception constr-decl in a signature requires the matching structure to provide an exception with the name and arguments specified in the definition, and makes the exception available to all users of the structure.

Class specifications

A specification of one or several classes in a signature is written class class-spec  { and class-spec } and consists of a sequence of mutually recursive definitions of class names.

Class specifications are described more precisely in section 6.9.4.

Class type specifications

A specification of one or several classe types in a signature is written class type classtype-def { and classtype-def } and consists of a sequence of mutually recursive definitions of class type names. Class type specifications are described more precisely in section 6.9.5.

Module specifications

A specification of a module component in a signature is written module module-name :  module-type, where module-name is the name of the module component and module-type its expected type. Modules can be nested arbitrarily; in particular, functors can appear as components of structures and functor types as components of signatures.

For specifying a module component that is a functor, one may write

module module-name (  name1 :  module-type1 )(  namen :  module-typen ) :  module-type

instead of

module module-name : functor (  name1 :  module-type1 ) ->->  module-type

Module type specifications

A module type component of a signature can be specified either as a manifest module type or as an abstract module type.

An abstract module type specification module type modtype-name allows the name modtype-name to be implemented by any module type in a matching signature, but hides the implementation of the module type to all users of the signature.

A manifest module type specification module type modtype-name =  module-type requires the name modtype-name to be implemented by the module type module-type in a matching signature, but makes the equality between modtype-name and module-type apparent to all users of the signature.

Opening a module path

The expression open module-path in a signature does not specify any components. It simply affects the parsing of the following items of the signature, allowing components of the module denoted by module-path to be referred to by their simple names name instead of path accesses module-path .  name. The scope of the open stops at the end of the signature expression.

Including a signature

The expression include module-type in a signature performs textual inclusion of the components of the signature denoted by module-type. It behaves as if the components of the included signature were copied at the location of the include. The module-type argument must refer to a module type that is a signature, not a functor type.

6.10.3  Functor types

The module type expression functor ( module-name :  module-type1 ) ->  module-type2 is the type of functors (functions from modules to modules) that take as argument a module of type module-type1 and return as result a module of type module-type2. The module type module-type2 can use the name module-name to refer to type components of the actual argument of the functor. No restrictions are placed on the type of the functor argument; in particular, a functor may take another functor as argument (“higher-order” functor).

6.10.4  The with operator

Assuming module-type denotes a signature, the expression module-type with  mod-constraint { and mod-constraint } denotes the same signature where type equations have been added to some of the type specifications, as described by the constraints following the with keyword. The constraint type [type-parameters]  typeconstr =  typexpr adds the type equation = typexpr to the specification of the type component named typeconstr of the constrained signature. The constraint module module-path =  extended-module-path adds type equations to all type components of the sub-structure denoted by module-path, making them equivalent to the corresponding type components of the structure denoted by extended-module-path.

For instance, if the module type name S is bound to the signature

        sig type t module M: (sig type u end) end

then S with type t=int denotes the signature

        sig type t=int module M: (sig type u end) end

and S with module M = N denotes the signature

        sig type t module M: (sig type u=N.u end) end

A functor taking two arguments of type S that share their t component is written

        functor (A: S) (B: S with type t = A.t) ...

Constraints are added left to right. After each constraint has been applied, the resulting signature must be a subtype of the signature before the constraint was applied. Thus, the with operator can only add information on the type components of a signature, but never remove information.

6.11  Module expressions (module implementations)

Module expressions are the module-level equivalent of value expressions: they evaluate to modules, thus providing implementations for the specifications expressed in module types.

module-expr::= module-path  
  struct { definition  [;;]  
  expr ;; } end  
  functor ( module-name :  module-type ) ->  module-expr  
  module-expr (  module-expr )  
  ( module-expr )  
  ( module-expr :  module-type )  
 
definition::= let [reclet-binding   { and let-binding }  
  external value-name :  typexpr =  external-declaration  
  type-definition  
  exception-definition  
  class-definition  
  classtype-definition  
  module module-name  { ( module-name :  module-type ) }  [ : module-type ]  =  module-expr  
  module type modtype-name =  module-type  
  open module-path  
  include module-expr

6.11.1  Simple module expressions

The expression module-path evaluates to the module bound to the name module-path.

The expression ( module-expr ) evaluates to the same module as module-expr.

The expression ( module-expr :  module-type ) checks that the type of module-expr is a subtype of module-type, that is, that all components specified in module-type are implemented in module-expr, and their implementation meets the requirements given in module-type. In other terms, it checks that the implementation module-expr meets the type specification module-type. The whole expression evaluates to the same module as module-expr, except that all components not specified in module-type are hidden and can no longer be accessed.

6.11.2  Structures

Structures structend are collections of definitions for value names, type names, exceptions, module names and module type names. The definitions are evaluated in the order in which they appear in the structure. The scope of the bindings performed by the definitions extend to the end of the structure. As a consequence, a definition may refer to names bound by earlier definitions in the same structure.

For compatibility with toplevel phrases (chapter 9) and with Caml Light, an optional ;; is allowed after each definition in a structure. The ;; has no semantic meaning. Also for compatibility, expr ;; is allowed as a component of a structure, meaning let _ = expr, i.e. evaluate expr for its side-effects. In this case, the ;; of the previous component is not optional.

Value definitions

A value definition let [rec] let-binding  { and let-binding } bind value names in the same way as a letin … expression (see section 6.7.1). The value names appearing in the left-hand sides of the bindings are bound to the corresponding values in the right-hand sides.

A value definition external value-name :  typexpr =  external-declaration implements value-name as the external function specified in external-declaration (see chapter 18).

Type definitions

A definition of one or several type components is written type typedef  { and typedef } and consists of a sequence of mutually recursive definitions of type names.

Exception definitions

Exceptions are defined with the syntax exception constr-decl or exception constr-name =  constr.

Class definitions

A definition of one or several classes is written class class-binding  { and class-binding } and consists of a sequence of mutually recursive definitions of class names. Class definitions are described more precisely in section 6.9.3.

Class type definitions

A definition of one or several classes is written class type classtype-def  { and classtype-def } and consists of a sequence of mutually recursive definitions of class type names. Class type definitions are described more precisely in section 6.9.5.

Module definitions

The basic form for defining a module component is module module-name =  module-expr, which evaluates module-expr and binds the result to the name module-name.

One can write

module module-name :  module-type =  module-expr

instead of

module module-name = (  module-expr :  module-type ).

Another derived form is

module module-name (  name1 :  module-type1 )(  namen :  module-typen ) =  module-expr

which is equivalent to

module module-name = functor (  name1 :  module-type1 ) ->->  module-expr

Module type definitions

A definition for a module type is written module type modtype-name =  module-type. It binds the name modtype-name to the module type denoted by the expression module-type.

Opening a module path

The expression open module-path in a structure does not define any components nor perform any bindings. It simply affects the parsing of the following items of the structure, allowing components of the module denoted by module-path to be referred to by their simple names name instead of path accesses module-path .  name. The scope of the open stops at the end of the structure expression.

Including the components of another structure

The expression include module-expr in a structure re-exports in the current structure all definitions of the structure denoted by module-expr. For instance, if the identifier S is bound to the module

        struct type t = int  let x = 2 end

the module expression

        struct include S  let y = (x + 1 : t) end

is equivalent to the module expression

        struct type t = int  let x = 2  let y = (x + 1 : t) end

The difference between open and include is that open simply provides short names for the components of the opened structure, without defining any components of the current structure, while include also adds definitions for the components of the included structure.

6.11.3  Functors

Functor definition

The expression functor ( module-name :  module-type ) ->  module-expr evaluates to a functor that takes as argument modules of the type module-type1, binds module-name to these modules, evaluates module-expr in the extended environment, and returns the resulting modules as results. No restrictions are placed on the type of the functor argument; in particular, a functor may take another functor as argument (“higher-order” functor).

Functor application

The expression module-expr1 (  module-expr2 ) evaluates module-expr1 to a functor and module-expr2 to a module, and applies the former to the latter. The type of module-expr2 must match the type expected for the arguments of the functor module-expr1.

6.12  Compilation units

unit-interface::= { specification  [;;] }  
 
unit-implementation::= { definition  [;;] }

Compilation units bridge the module system and the separate compilation system. A compilation unit is composed of two parts: an interface and an implementation. The interface contains a sequence of specifications, just as the inside of a sigend signature expression. The implementation contains a sequence of definitions, just as the inside of a structend module expression. A compilation unit also has a name unit-name, derived from the names of the files containing the interface and the implementation (see chapter 8 for more details). A compilation unit behaves roughly as the module definition

module unit-name : sig  unit-interface end = struct  unit-implementation end

A compilation unit can refer to other compilation units by their names, as if they were regular modules. For instance, if U is a compilation unit that defines a type t, other compilation units can refer to that type under the name U.t; they can also refer to U as a whole structure. Except for names of other compilation units, a unit interface or unit implementation must not have any other free variables. In other terms, the type-checking and compilation of an interface or implementation proceeds in the initial environment

name1 : sig  specification1 end …  namen : sig  specificationn end

where name1 …  namen are the names of the other compilation units available in the search path (see chapter 8 for more details) and specification1 …  specificationn are their respective interfaces.

Chapter 7  Language extensions

This chapter describes language extensions and convenience features that are implemented in Objective Caml, but not described in the Objective Caml reference manual.

7.1  Integer literals for types int32, int64 and nativeint

int32-literal::= integer-literal l  
 
int64-literal::= integer-literal L  
 
nativeint-literal::= integer-literal n

An integer literal can be followed by one of the letters l, L or n to indicate that this integer has type int32, int64 or nativeint respectively, instead of the default type int for integer literals. The library modules Int32[Int32], Int64[Int64] and Nativeint[Nativeint] provide operations on these integer types.

7.2  Streams and stream parsers

The syntax for streams and stream parsers is no longer part of the Objective Caml language, but available through a Camlp4 syntax extension. See the Camlp4 reference manual for more information. Support for basic operations on streams is still available through the Stream[Stream] module of the standard library. Objective Caml programs that use the stream parser syntax should be compiled with the -pp camlp4o option to ocamlc and ocamlopt. For interactive use, run ocaml and issue the #load "camlp4o.cma";; command.

7.3  Recursive definitions of values

As mentioned in section 6.7.1, the let rec binding construct, in addition to the definition of recursive functions, also supports a certain class of recursive definitions of non-functional values, such as

let rec name1 = 1 ::  name2 and  name2 = 2 ::  name1 in  expr

which binds name1 to the cyclic list 1::2::1::2::…, and name2 to the cyclic list 2::1::2::1::…Informally, the class of accepted definitions consists of those definitions where the defined names occur only inside function bodies or as argument to a data constructor.

More precisely, consider the expression:

let rec name1 =  expr1 andand  namen =  exprn in  expr

It will be accepted if each one of expr1 …  exprn is statically constructive with respect to name1 …  namen and not immediately linked to any of name1 …  namen

An expression e is said to be statically constructive with respect to the variables name1 …  namen if at least one of the following conditions is true:

An expression e is said to be immediately linked to the variable name in the following cases:

7.4  Range patterns

In patterns, Objective Caml recognizes the form ' c ' .. ' d ' (two character literals separated by ..) as shorthand for the pattern

' c ' | ' c1 ' | ' c2 ' || ' cn ' | ' d '

where c1, c2, …, cn are the characters that occur between c and d in the ASCII character set. For instance, the pattern '0'..'9' matches all characters that are digits.

7.5  Assertion checking

Objective Caml supports the assert construct to check debugging assertions. The expression assert expr evaluates the expression expr and returns () if expr evaluates to true. Otherwise, the exception Assert_failure is raised with the source file name and the location of expr as arguments. Assertion checking can be turned off with the -noassert compiler option.

As a special case, assert false is reduced to raise (Assert_failure ...), which is polymorphic (and is not turned off by the -noassert option).

7.6  Lazy evaluation

The expression lazy expr returns a value v of type Lazy.t that encapsulates the computation of expr. The argument expr is not evaluated at this point in the program. Instead, its evaluation will be performed the first time Lazy.force is applied to the value v, returning the actual value of expr. Subsequent applications of Lazy.force to v do not evaluate expr again. Applications of Lazy.force may be implicit through pattern matching.

The pattern lazy pattern matches values v of type Lazy.t, provided pattern matches the result of forcing v with Lazy.force. A successful match of a pattern containing lazy sub-patterns forces the corresponding parts of the value being matched, even those that imply no test such as lazy value-name or lazy _. Matching a value with a pattern-matching where some patterns contain lazy sub-patterns may imply forcing parts of the value, even when the pattern selected in the end has no lazy sub-pattern.

For more information, see the description of module Lazy in the standard library (see Module Lazy).

7.7  Local modules

The expression let module module-name =  module-expr in  expr locally binds the module expression module-expr to the identifier module-name during the evaluation of the expression expr. It then returns the value of expr. For example:

        let remove_duplicates comparison_fun string_list =
          let module StringSet =
            Set.Make(struct type t = string
                            let compare = comparison_fun end) in
          StringSet.elements
            (List.fold_right StringSet.add string_list StringSet.empty)

7.8  Recursive modules

definition::= ...  
  module rec module-name :  module-type =  module-expr   { and module-name:  module-type =  module-expr }  
 
specification::= ...  
  module rec module-name :  module-type  { and module-name:  module-type }

Recursive module definitions, introduced by the 'module rec' …'and' … construction, generalize regular module definitions module module-name =  module-expr and module specifications module module-name :  module-type by allowing the defining module-expr and the module-type to refer recursively to the module identifiers being defined. A typical example of a recursive module definition is:

    module rec A : sig
                     type t = Leaf of string | Node of ASet.t
                     val compare: t -> t -> int
                   end
                 = struct
                     type t = Leaf of string | Node of ASet.t
                     let compare t1 t2 =
                       match (t1, t2) with
                         (Leaf s1, Leaf s2) -> Pervasives.compare s1 s2
                       | (Leaf _, Node _) -> 1
                       | (Node _, Leaf _) -> -1
                       | (Node n1, Node n2) -> ASet.compare n1 n2
                   end
        and ASet : Set.S with type elt = A.t
                 = Set.Make(A)

It can be given the following specification:

    module rec A : sig
                     type t = Leaf of string | Node of ASet.t
                     val compare: t -> t -> int
                   end
        and ASet : Set.S with type elt = A.t

This is an experimental extension of Objective Caml: the class of recursive definitions accepted, as well as its dynamic semantics are not final and subject to change in future releases.

Currently, the compiler requires that all dependency cycles between the recursively-defined module identifiers go through at least one “safe” module. A module is “safe” if all value definitions that it contains have function types typexpr1 ->  typexpr2. Evaluation of a recursive module definition proceeds by building initial values for the safe modules involved, binding all (functional) values to fun _ -> raise Undefined_recursive_module. The defining module expressions are then evaluated, and the initial values for the safe modules are replaced by the values thus computed. If a function component of a safe module is applied during this computation (which corresponds to an ill-founded recursive definition), the Undefined_recursive_module exception is raised.

7.9  Private types

Private type declarations in module signatures, of the form type t = private ..., enable libraries to reveal some, but not all aspects of the implementation of a type to clients of the library. In this respect, they strike a middle ground between abstract type declarations, where no information is revealed on the type implementation, and data type definitions and type abbreviations, where all aspects of the type implementation are publicized. Private type declarations come in three flavors: for variant and record types (section 7.9.1), for type abbreviations (section 7.9.2), and for row types (section 7.9.3).

7.9.1  Private variant and record types

type-representation::= ...  
  = private constr-decl  { | constr-decl }  
  = private { field-decl  { ; field-decl } }

Values of a variant or record type declared private can be de-structured normally in pattern-matching or via the expr .  field notation for record accesses. However, values of these types cannot be constructed directly by constructor application or record construction. Moreover, assignment on a mutable field of a private record type is not allowed.

The typical use of private types is in the export signature of a module, to ensure that construction of values of the private type always go through the functions provided by the module, while still allowing pattern-matching outside the defining module. For example:

        module M : sig
                     type t = private A | B of int
                     val a : t
                     val b : int -> t
                   end
                 = struct
                     type t = A | B of int
                     let a = A
                     let b n = assert (n > 0); B n
                   end

Here, the private declaration ensures that in any value of type M.t, the argument to the B constructor is always a positive integer.

With respect to the variance of their parameters, private types are handled like abstract types. That is, if a private type has parameters, their variance is the one explicitly given by prefixing the parameter by a `+' or a `-', it is invariant otherwise.

7.9.2  Private type abbreviations

type-equation::= ...  
  = private typexpr

Unlike a regular type abbreviation, a private type abbreviation declares a type that is distinct from its implementation type typexpr. However, coercions from the type to typexpr are permitted. Moreover, the compiler “knows” the implementation type and can take advantage of this knowledge to perform type-directed optimizations. For ambiguity reasons, typexp