The Objective Caml system release 1.02 Documentation and user's manual Xavier Leroy September 27, 1996 Copyright oc 1996 Institut National de Recherche en Informatique et Automatique Contents I An introduction to Objective Caml 6 1 The core language 7 2 Objects in Caml 19 3 The module system 28 II The Objective Caml language 36 4 The Objective Caml language 37 4.1 Lexical conventions . . . . . . . . . . . . . . . . . . . . . . . 37 4.2 Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 4.3 Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 4.4 Type expressions. . . . . . . . . . . . . . . . . . . . . . . . . 43 4.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.6 Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.7 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.8 Type and exception definitions. . . . . . . . . . . . . . . . . . 55 4.9 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.10 Module types (module specifications). . . . . . . . . . . . . . . 59 4.11 Module expressions (module implementations) . . . . . . . . . . . 62 4.12 Compilation units . . . . . . . . . . . . . . . . . . . . . . . . 65 5 Language extensions 66 5.1 Streams and stream parsers. . . . . . . . . . . . . . . . . . . . 66 5.2 Range patterns. . . . . . . . . . . . . . . . . . . . . . . . . . 67 III The Objective Caml tools 68 6 Batch compilation (ocamlc) 69 6.1 Overview of the compiler. . . . . . . . . . . . . . . . . . . . . 69 6.2 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 6.3 Modules and the file system . . . . . . . . . . . . . . . . . . . 72 6.4 Common errors . . . . . . . . . . . . . . . . . . . . . . . . . . 72 7 The toplevel system (ocaml) 76 7.1 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 7.2 Toplevel directives . . . . . . . . . . . . . . . . . . . . . . . 78 7.3 The toplevel and the module system. . . . . . . . . . . . . . . . 79 7.4 Common errors . . . . . . . . . . . . . . . . . . . . . . . . . . 79 7.5 Building custom toplevel systems: ocamlmktop . . . . . . . . . . 80 7.6 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 8 The runtime system (ocamlrun) 82 8.1 Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 8.2 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 1 2 8.3 Common errors . . . . . . . . . . . . . . . . . . . . . . . . . . 83 9 Native-code compilation (ocamlopt) 85 9.1 Overview of the compiler. . . . . . . . . . . . . . . . . . . . . 85 9.2 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 9.3 Common errors . . . . . . . . . . . . . . . . . . . . . . . . . . 87 9.4 Compatibility with the bytecode compiler. . . . . . . . . . . . . 87 10 Lexer and parser generators (ocamllex, ocamlyacc) 89 10.1 Overview of ocamllex. . . . . . . . . . . . . . . . . . . . . . . 89 10.2 Syntax of lexer definitions . . . . . . . . . . . . . . . . . . . 89 10.3 Overview of ocamlyacc . . . . . . . . . . . . . . . . . . . . . . 91 10.4 Syntax of grammar definitions . . . . . . . . . . . . . . . . . . 92 10.5 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 10.6 A complete example. . . . . . . . . . . . . . . . . . . . . . . . 94 11 Dependency generator (ocamldep) 96 11.1 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 11.2 A typical Makefile. . . . . . . . . . . . . . . . . . . . . . . . 96 12 Profiling (ocamlprof) 98 12.1 Compiling for profiling . . . . . . . . . . . . . . . . . . . . . 98 12.2 Profiling an execution. . . . . . . . . . . . . . . . . . . . . . 98 12.3 Printing profiling information. . . . . . . . . . . . . . . . . . 99 12.4 Time profiling. . . . . . . . . . . . . . . . . . . . . . . . . . 99 13 Interfacing C with Objective Caml 100 13.1 Overview and compilation information. . . . . . . . . . . . . . . 100 13.2 The value type. . . . . . . . . . . . . . . . . . . . . . . . . . 103 13.3 Representation of Caml Light data types . . . . . . . . . . . . . 104 13.4 Operations on values. . . . . . . . . . . . . . . . . . . . . . . 105 13.5 Living in harmony with the garbage collector. . . . . . . . . . . 108 13.6 A complete example. . . . . . . . . . . . . . . . . . . . . . . . 110 IV The Objective Caml library 113 14 The core library 114 14.1 Module Pervasives: the initially opened module . . . . . . . . . 114 15 The standard library 128 15.1 Module Arg: parsing of command line arguments. . . . . . . . . . 129 15.2 Module Array: array operations . . . . . . . . . . . . . . . . . 130 15.3 Module Char: character operations. . . . . . . . . . . . . . . . 131 15.4 Module Digest: MD5 message digest. . . . . . . . . . . . . . . . 132 15.5 Module Filename: operations on file names. . . . . . . . . . . . 132 15.6 Module Format: pretty printing . . . . . . . . . . . . . . . . . 133 15.7 Module Gc: memory management control and statistics. . . . . . . 139 15.8 Module Genlex: a generic lexical analyzer. . . . . . . . . . . . 140 15.9 Module Hashtbl: hash tables and hash functions . . . . . . . . . 141 15.10 Module Lexing: the run-time library for lexers generated by camllex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 15.11Module List: list operations . . . . . . . . . . . . . . . . . . 144 15.12Module Map: association tables over ordered types. . . . . . . . 146 15.13Module Oo: object-oriented extension . . . . . . . . . . . . . . 148 15.14Module Parsing: the run-time library for parsers generated by camlyacc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 15.15Module Printexc: a catch-all exception handler . . . . . . . . . 148 15.16Module Printf: formatting printing functions . . . . . . . . . . 149 3 15.17Module Queue: first-in first-out queues. . . . . . . . . . . . . 150 15.18Module Random: pseudo-random number generator. . . . . . . . . . 150 15.19Module Set: sets over ordered types. . . . . . . . . . . . . . . 151 15.20Module Sort: sorting and merging lists . . . . . . . . . . . . . 153 15.21Module Stack: last-in first-out stacks . . . . . . . . . . . . . 153 15.22Module Stream: streams and stream parsers operations . . . . . . 154 15.23Module String: string operations . . . . . . . . . . . . . . . . 155 15.24Module Sys: system interface . . . . . . . . . . . . . . . . . . 156 16 The unix library: Unix system calls 159 16.1 Module Unix: interface to the Unix system. . . . . . . . . . . . 160 17 The num library: arbitrary-precision rational arithmetic 180 17.1 Module Num: operation on arbitrary-precision numbers . . . . . . 181 17.2 Module Arith_status: flags that control rational arithmetic. . . 183 18 The str library: regular expressions and string processing 185 18.1 Module Str: regular expressions and high-level string processing 185 19 The threads library 189 19.1 Module Thread: user-level lightweight threads. . . . . . . . . . 189 19.2 Module Mutex: locks for mutual exclusion . . . . . . . . . . . . 191 19.3 Module Condition: condition variables to synchronize between threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 19.4 Module Event: first-class synchronous communication. . . . . . . 192 19.5 Module ThreadUnix: thread-compatible system calls. . . . . . . . 193 20 The graphics library 196 20.1 Module Graphics: machine-independent graphics primitives . . . . 197 21 The dbm library: access to NDBM databases 203 21.1 Module Dbm: interface to the NDBM databases. . . . . . . . . . . 203 V Appendix 205 Index to the library 206 Index of keywords 213 Foreword This manual documents the release 1.02 of the Objective Caml system. It is organized as follows. - Part I, ``An introduction to Objective Caml'', gives an overview of the language. - Part II, ``The Objective Caml language'', is the reference description of the language. - Part III, ``The Objective Caml tools, documents the compilers, toplevel system, and programming utilities. - Part IV, ``The Objective Caml library'', describes the modules provided in the standard library. - Part V, ``Appendix'', contains an index of all identifiers defined in the standard library, and an index of keywords. 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 Unix. Windows: This is material specific to MS Windows (NT and 95). License c The Objective Caml system is copyright o 1996 Institut National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership rights to the Objective Caml system. See the file LICENSE in the distribution for licensing information. The Objective Caml system can be freely copied, but not sold. More precisely, INRIA grants any user of the Objective Caml system the right to reproduce it, provided that the copies are distributed free of charge and under the conditions given in the LICENSE file. The present documentation is distributed under the same conditions. Availability The complete Objective Caml distribution resides on the machine ftp.inria.fr. The distribution files can be transferred by anonymous FTP: 4 5 Host: ftp.inria.fr (Internet address 192.93.2.54) Login name: anonymous Password: your e-mail address Directory: lang/caml-light Files: see the index in file README More information on the Caml family of languages is also available on the World Wide Web, http://pauillac.inria.fr/caml/. Part I An introduction to Objective Caml 6 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 2 deals with the object-oriented features, and chapter 3 with the module system. 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.14159265359 #let square x = x *. x;; val square : float -> float = #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;; Characters 0-3: 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 = 7 Chapter 1. The core language 8 # if n < 2 then 1 else fib(n-1) + fib(n-2);; val fib : int -> int = #fib 10;; - : int = 89 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 = val insert : 'a -> 'a list -> 'a list = #sort l;; - : string list = ["a"; "etc."; "is"; "tale"; "told"] Chapter 1. The core language 9 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. This is because 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. 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 = #let cos' = deriv sin 1e-6;; val cos' : float -> float = #cos' pi;; - : float = -1.00000000014 Even function composition is definable: #let compose f g = function x -> f(g(x));; val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = #let cos2 = compose square cos;; val cos2 : float -> float = 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 Chapter 1. The core language 10 # [] -> [] # | hd :: tl -> f hd :: map f tl;; val map : ('a -> 'b) -> 'a list -> 'b list = 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 = #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 = 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 Chapter 1. The core language 11 # | (_, Error) -> Error;; val add_num : number -> number -> number = #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 = #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 = 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 = #add_vect [| 1.0; 2.0 |] [| 3.0; 4.0 |];; - : float array = [|4; 6|] Chapter 1. The core language 12 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 = #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) do # a.(!j) <- a.(!j - 1); # j := !j - 1 # done; # a.(!j) <- val_i # done;; val insertion_sort : 'a array -> unit = 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 = 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;; Chapter 1. The core language 13 val ! : 'a ref -> 'a = #let (:=) r newval = r.contents <- newval;; val := : 'a ref -> 'a -> unit = Exceptions Caml provides exceptions for signalling and handling exceptional conditions. Exceptions can also be used as a general-purpose non-local control structures. 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 = #head [1;2];; - : int = 1 #head [];; Uncaught 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")];; Uncaught exception: Not_found Exceptions can be trapped with the try...with 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 = #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 try...with construct. Also, Chapter 1. The core language 14 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 = 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 = #eval [("x", 1.0); ("y", 3.14)] (Prod(Sum(Var "x", Const 2.0), Var "y"));; Chapter 1. The core language 15 - : 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 = #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")) 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 Chapter 1. The core language 16 # | 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 = #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 10), 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 10. Here, we will use stream parsers. #open Genlex;; #let lexer = make_lexer ["("; ")"; "+"; "-"; "*"; "/"];; val lexer : char Stream.t -> Genlex.token Stream.t = 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 = #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 chapter 5 for more details. Chapter 1. The core language 17 #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 = val parse_more_adds : expression -> Genlex.token Stream.t -> expression = val parse_mult : Genlex.token Stream.t -> expression = val parse_more_mults : expression -> Genlex.token Stream.t -> expression = val parse_simple : Genlex.token Stream.t -> expression = Composing the lexer and parser, we finally obtain a function to read an expression from a character string: #let read_expr s = parse_expr(lexer(Stream.of_string s));; val read_expr : string -> expression = #read_expr "2*(x+y)";; - : expression = Prod (Const 2, Sum (Var "x", Var "y")) 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 ();; Chapter 1. The core language 18 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 Objects in Caml This chapter gives an overview of the object-oriented features of Objective Caml. Classes and objects The class point has one instance variable x and two methods get_x and move. The initial value of the instance variable is given here by the class parameter x_init. The variable x is declared mutable, so the method move can change its value. #class point x_init = # val mutable x = x_init # method get_x = x # method move d = x <- x + d #end;; class point (int) = val mutable x : int method get_x : int method move : int -> unit end We now create a new point p, giving the initialization argument 7. #let p = new point 7;; val p : point = 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. Let us apply some methods to p: #p#get_x;; - : int = 7 #p#move 3;; - : unit = () #p#get_x;; - : int = 10 The library function Oo.copy copies an object. Its type is < .. > as 'a -> 'a. The keyword as in that type binds the type variable 'a to the object type 19 Chapter 2. Objects in Caml 20 < .. >. Oo.copy therefore 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 q = Oo.copy p;; val q : point = #q#move 7; (p#get_x, q#get_x);; - : int * int = 10, 17 Inheritance We now define a new class color_point. This class inherits from class point. So, it has all the instance variable and all the methods of point, plus a new instance variable c and a new method color. #class color_point x (c : string) = # inherit point x # val c = c # method color = c #end;; class color_point (int) (string) = val c : string val mutable x : int method get_x : int method move : int -> unit method color : string end #let p' = new color_point 5 "red";; val p' : color_point = #p'#get_x, p'#color;; - : int * string = 5, "red" A point and a color point have incompatible types: a point has no method color. Thus, if one wants to put p and p' in the same list, one needs to coerce p' to the type of points, hiding its color method. #let l = [p; (p' :> point)];; val l : point list = [; ] The function get_x below is a generic function applying method get_x to any object p which has this method (and possibly some others, which are represented by an ellipsis in the type). The method needs not be declared previously, as shown by the companion function set_x. Function get_x can then be mapped on list l. #let get_x p = p#get_x;; val get_x : < get_x : 'a; .. > -> 'a = #let set_x p = p#set_x;; val set_x : < set_x : 'a; .. > -> 'a = #List.map get_x l;; - : int list = [10; 5] Chapter 2. Objects in Caml 21 Parameterized classes Reference cells can also be implemented as objects: #class ref x_init = # val mutable x = x_init # method get = x # method set y = x <- y #end;; Characters 5-85: The type variable 'a is not bound in implicit type definition ref = < get : 'a; set : 'a -> unit > It should be captured by a class type parameter The reason why this definition does not typecheck is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus the class should be parametric. A monomorphic instance of the class could be defined by: #class ref (x_init:int) = # val mutable x = x_init # method get = x # method set y = x <- y #end;; class ref (int) = val mutable x : int method get : int method set : int -> unit end A class for polymorphic references must explicitly list the type parameters in its declaration. The type parameters must also be bound somewhere in the class body by a type constraint. #class 'a ref x_init = # val mutable x = (x_init : 'a) # method get = x # method set y = x <- y #end;; class 'a ref ('a) = 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 (x_init:'a) = # val mutable x = x_init + 1 # method get = x # method set y = x <- y #end;; class 'a ref ('a) = Chapter 2. Objects in Caml 22 constraint 'a = int val mutable x : int method get : int method set : int -> unit end Let us consider a more realistic example. We put an additional type constraint in method move, since no free variables must remain uncaptured by a type parameter. #class 'a circle (c : 'a) = # val mutable center = c # method center = center # method set_center c = center <- c # method move = (center#move : int -> unit) #end;; class 'a circle ('a) = constraint 'a = < move : int -> unit; .. > val mutable center : 'a method center : 'a method set_center : 'a -> unit method move : int -> 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) = # 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) = constraint 'a = #point val mutable center : 'a method center : 'a method set_center : 'a -> unit method move : int -> unit end The class color_circle is a specialized version of class circle which requires the type of the center to unify with #color_point, and adds a method color. #class 'a color_circle c = # constraint 'a = #color_point # inherit ('a) circle c # method color = center#color #end;; class 'a color_circle ('a) = Chapter 2. Objects in Caml 23 constraint 'a = < get_x : int; move : int -> unit; color : string; .. > val mutable center : 'a method center : 'a method set_center : 'a -> unit method move : int -> unit method color : string end Self reference A method can also send messages to the object that invoked the method. For that, self must be explicitly bound, here to the variable s. #class printable_point y as s = # inherit point y # method print = print_int s#get_x #end;; class printable_point (int) = 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 = #p#print;; 7- : unit = () The variable s is bound at the invocation of a method. In particular, if the class printable_point is inherited, the variable s will correctly be bound to an object of the subclass. Multiple inheritance Multiple inheritance is allowed. Only the last definition of a method (or of an instance variable) is kept. But previous definitions of a method can be reused by binding the related ancestor. Here, super is bound to the ancestor printable_point. The name super is not actually a variable and can only be used to select a method as in super#print. #class printable_color_point y c as self = # inherit color_point y c # inherit printable_point y as super # method print = # print_string "("; # super#print; # print_string ", "; # print_string (self#color); # print_string ")" #end;; class printable_color_point (int) (string) = val c : string val mutable x : int method get_x : int Chapter 2. Objects in Caml 24 method move : int -> unit method color : string method print : unit end #let p' = new printable_color_point 7 "red";; val p' : printable_color_point = #p'#print;; (7, red)- : unit = () Non-mutable 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 = # val x = y # method get_x = x # method move d = {< x = x + d >} #end;; class functional_point (int) : 'a = val x : int method get_x : int method move : int -> 'a end #let p = new functional_point 7;; val p : functional_point = #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 to 'a and 'a appears inside the type of the move method. Virtual methods 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. Since this class has a method declared but not defined, it must be flagged virtual and cannot be instantiated (that is, no object of this class can be created). It still defines abbreviations. In particular, #comparable expands to < leq : 'a -> bool; .. > as 'a. We see here that the binder as also allows to write recursive types. #class virtual comparable () : 'a = Chapter 2. Objects in Caml 25 # virtual leq : 'a -> bool #end;; class virtual comparable (unit) : 'a = virtual leq : 'a -> bool end We then defines a subclass of comparable, which wraps integers as comparable objects. 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 int_comparable (x : int) = # inherit comparable () # val x = x # method x = x # method leq p = x <= p#x #end;; class int_comparable (int) : 'a = val x : int method leq : 'a -> bool method x : int end Objects of class int_comparable2 below can also modify the integer they hold. The status of instance variable x is changed. It is now mutable and private; that is, subclasses cannot access it (it does no longer appear in the class type). Note that the type int_comparable2 is not a subtype of type int_comparable, as the self type appears in contravariant position in the type of method leq. #class int_comparable2 x = # inherit int_comparable x # val private mutable x # method set_x y = x <- y #end;; class int_comparable2 (int) : 'a = method leq : 'a -> bool method x : int method set_x : int -> unit end The function min will return the minimum of any two objects whose type unify 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 = This function can be applied to objects of type int_comparable or int_comparable2. #(min (new int_comparable 7) (new int_comparable 11))#x;; - : int = 7 #(min (new int_comparable2 5) (new int_comparable2 3))#x;; - : int = 3 Chapter 2. Objects in Caml 26 Recursive classes This last example is somewhat more complicated. It demonstrates recursive classes. Indeed, lists can also be implemented by classes. We recursively define three classes: 1. A virtual class lst implements functional over lists, here a map method, an interation method, and a printing method. 2. A class nil defines the behavior of the empty list. 3. A class cons defines the behavior of non-empty lists. All three classes have the same interface. The class lst depends on classes nil and cons since the map method creates objets of the classes nil and cons, which themselves depend on the class lst, since they both inherits the class lst. #class virtual 'a lst () as self = # virtual null : bool # virtual hd : 'a # virtual tl : 'a lst # method map f = # (if self#null then # new nil () # else # new cons (f self#hd) (self#tl#map f) # : 'a lst) # method iter (f : 'a -> unit) = # if self#null then () # else begin # f self#hd; # self#tl#iter f # end # method print (f : 'a -> unit) = # print_string "("; # self#iter (fun x -> f x; print_string "::"); # print_string "[]"; # print_string ")" #and 'a nil () = # inherit ('a) lst () # method null = true # method hd = failwith "hd" # method tl = failwith "tl" # #and 'a cons h t = # inherit ('a) lst () # val h = h val t = t # method null = false # method hd = h # method tl = t #end;; class virtual 'a lst (unit) = method map : ('a -> 'a) -> 'a lst method iter : ('a -> unit) -> unit method print : ('a -> unit) -> unit virtual null : bool virtual hd : 'a Chapter 2. Objects in Caml 27 virtual tl : 'a lst end class 'a nil (unit) = method null : bool method hd : 'a method tl : 'a lst method map : ('a -> 'a) -> 'a lst method iter : ('a -> unit) -> unit method print : ('a -> unit) -> unit end class 'a cons ('a) ('a lst) = val h : 'a val t : 'a lst method null : bool method hd : 'a method tl : 'a lst method map : ('a -> 'a) -> 'a lst method iter : ('a -> unit) -> unit method print : ('a -> unit) -> unit end It is a weakness of Objective Caml that objects cannot have polymorphic methods: the method map can only return a list of the same type as the objet to which it applies. #let l1 = new cons 3 (new cons 10 (new nil ()));; val l1 : int cons = #l1#print print_int;; (3::10::[])- : unit = () #let l2 = l1#map (fun x -> x + 1);; val l2 : int lst = #l2#print print_int;; (4::11::[])- : unit = () A polymorphic map function can still be defined: #let rec map_list f (x:'a lst) = # if x#null then new nil() # else new cons (f x#hd) (map_list f x#tl);; val map_list : ('a -> 'b) -> 'a lst -> 'b lst = #let p1 = (map_list (fun x -> new printable_color_point x "red") l1);; val p1 : printable_color_point lst = #p1#print (fun x -> x#print);; ((3, red)::(10, red)::[])- : unit = () Chapter 3 The module system This chapter introduces the module system of Objective Caml. 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 struct...end 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 28 Chapter 3. The module system 29 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) 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;; Characters 0-28: Unbound value AbstractPrioQueue.remove_top Chapter 3. The module system 30 #AbstractPrioQueue.insert AbstractPrioQueue.empty 1 "hello";; - : string AbstractPrioQueue.queue = 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;; 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 B1,...,Bn of B, yielding the corresponding structures A1,...,An. 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 cmp: t -> t -> comparison # end;; module type ORDERED_TYPE = sig type t val cmp : 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.cmp 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.cmp 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 : Chapter 3. The module system 31 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 cmp x y = if x = y then Equal else if x < y then Less else Greater # end;; module OrderedString : sig type t = string val cmp : '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 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 Chapter 3. The module system 32 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 = 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;; Characters 19-24: This expression has type string but is here used with type WrongStringSet.element = WrongSet(OrderedString).element Chapter 3. The module system 33 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 allow 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 normalize s = (* Convert to lowercase *) # let r = String.copy s in # for i = 0 to String.length r - 1 do # if r.[i] >= 'A' && r.[i] <= 'Z' then # r.[i] <- Char.chr(Char.code r.[i] + 32) # done; # r # let cmp s1 s2 = OrderedString.cmp (normalize s1) (normalize s2) # end;; module NoCaseString : sig type t = string val normalize : string -> string val cmp : string -> string -> comparison end #module NoCaseStringSet = AbstractSet(NoCaseString);; module NoCaseStringSet : sig type element = NoCaseString.t type set = AbstractSet(NoCaseString).set Chapter 3. The module system 34 val empty : set val add : element -> set -> set val member : element -> set -> bool end #NoCaseStringSet.add "FOO" AbstractStringSet.empty;; Characters 26-49: 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. 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: - the implementation file a.ml, which contains a sequence of definitions, analogous to the inside of a struct...end construct; - the interface file a.mli, which contains a sequence of specifications, analogous to the inside of a sig...end construct. Both files define a structure named A (same name as the base name a of the two files, with the first letter capitalized), 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 ocaml -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 Chapter 3. The module system 35 $ 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. Part II The Objective Caml language 36 Chapter 4 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. 4.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. 37 Chapter 4. The Objective Caml language 38 Identifiers ident ::= letter {letter | 0...9 | _ | '} letter ::= A...Z | a...z Identifiers are sequences of letters, digits, _ (the underscore character), and ' (the single quote), starting with a letter. 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 places no limits on the number of characters of an identifier. Integer literals integer-literal ::= [-] {0...9}+ | [-] (0x | 0X) {0...9 | A...F | a...f}+ | [-] (0o | 0O) {0...7}+ | [-] (0b | 0B) {0...1}+ 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: -------------------------------- |Prefix|Radix | -------------------------------- |0x, 0X|hexadecimal (radix 16) | |0o, 0O|octal (radix 8) | |0b, 0B|binary (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. Floating-point literals float-literal ::= [-] {0...9}+ [. {0...9}] [(e | E) [+ | -] {0...9}+] 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. Character literals char-literal ::= ' regular-char ' | ' \ (\ | ' | n | t | b | r) ' | ' \ (0...9) (0...9) (0...9) ' 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: Chapter 4. The Objective Caml language 39 -------------------------------------------------------- |Sequence|Character denoted | -------------------------------------------------------- |\\ |backslash (\) | |\' |single quote (') | |\n |newline (LF) | |\r |return (CR) | |\t |horizontal tabulation (TAB) | |\b |backspace (BS) | |\ddd |the character with ASCII code ddd in decimal | -------------------------------------------------------- String literals string-literal ::= " {string-character} " string-character ::= regular-char | \ (\ | " | n | t | b | r) | \ (0...9) (0...9) (0...9) 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 below: -------------------------------------------------------- |Sequence|Character denoted | -------------------------------------------------------- |\\ |backslash (\) | |\" |double quote (") | |\n |newline (LF) | |\r |return (CR) | |\t |horizontal tabulation (TAB) | |\b |backspace (BS) | |\ddd |the character with ASCII code ddd in decimal | -------------------------------------------------------- The current implementation places no restrictions on the length of string literals. 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 asr begin class closed constraint do done downto else end exception external false for fun function functor if in include inherit land let lor lsl lsr lxor match method mod module mutable new of open or parser private rec sig struct then to true try type Chapter 4. The Objective Caml language 40 val virtual when while with The following character sequences are also keywords: # & ' ( ) * , -> ? . .. .( .[ : :: := ; ;; <- = [ [| [< {< ] |] >] >} _ { | } 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. 4.2 Values This section describes the kinds of values that are manipulated by Caml Light programs. 4.2.1 Base values Integer numbers 30 30 Integer values are integer numbers from -2 to 2 -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 62 62 ranging from -2 to 2 -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 24 supports strings containing up to 2 -6 characters (16777210 characters). 4.2.2 Tuples Tuples of values are written (v1,...,vn), standing for the n-tuple of values 22 v1 to vn. The current implementation supports tuple of up to 2 -1 elements Chapter 4. The Objective Caml language 41 (4194303 elements). 4.2.3 Records Record values are labeled tuples of values. The record value written {label1=v1 ;...;labeln =vn} associates the value vi to the record label labeli, for i=1...n. The current implementation supports records with up to 22 2 -1 fields (4194303 fields). 4.2.4 Arrays Arrays are finite, variable-sized sequences of values of the same type. The 22 current implementation supports arrays containing to 2 -1 elements (4194303 elements). 4.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 cconstr; the latter case is written ncconstr(v), where v is said to be the argument of the non-constant constructor ncconstr. The following constants are treated like built-in constant constructors: ------------------------------ |Constant|Constructor | ------------------------------ |false |the boolean false | |true |the boolean true | |() |the ``unit'' value | |[] |the empty list | ------------------------------ The current implementation limits the number of distinct constructors in a given variant type to at most 249. 4.2.6 Functions Functional values are mappings from values to values. 4.2.7 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. 4.3 Names Identifiers are used to give names to several classes of language objects and refer to these objects by name later: - value names (syntactic class value-name), - value constructors (constant -- class cconstr-name -- or non-constant -- class ncconstr-name), - type constructors (typeconstr-name), Chapter 4. The Objective Caml language 42 - record labels (label-name), - class names (class-name), - method names (method-name), - instance variable names (inst-var-name), - module names (module-name), - module type names (modtype-name). These nine 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). Naming objects value-name ::= lowercase-ident | ( operator-name ) operator-name ::= prefix-symbol | infix-symbol | * | = | or | & | := cconstr-name ::= capitalized-ident | false | true | [ ] | ( ) ncconstr-name ::= capitalized-ident | :: typeconstr-name ::= lowercase-ident label-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. Keywords such as '::' and 'false' are also constructor names. The capitalization rules are summarized in the table below. ----------------------------------------- |Name space |Case of first letter | ----------------------------------------- |Values |lowercase | |Constructors |uppercase | |Type constructors |lowercase | |Record labels |lowercase | |Classes |lowercase | |Methods |lowercase | |Modules |uppercase | |Module types |any | ----------------------------------------- Chapter 4. The Objective Caml language 43 Referring to named objects value-path ::= value-name | module-path . lowercase-ident cconstr ::= cconstr-name | module-path . capitalized-ident ncconstr ::= ncconstr-name | module-path . capitalized-ident typeconstr ::= typeconstr-name | extended-module-path . lowercase-ident label ::= label-name | module-path . lowercase-ident module-path ::= module-name | module-path . capitalized-ident extended-module-path ::= module-name | extended-module-path . capitalized-ident | extended-module-path ( extended-module-path ) modtype-path ::= modtype-name | extended-module-path . ident class-path ::= class-name | module-path . lowercase-ident 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. Instance variable names and method names need not be qualified: the former are local to a class while the latter are global labels. 4.4 Type expressions typexpr ::= ' ident | ( typexpr ) | typexpr -> typexpr | typexpr {* typexpr}+ | typeconstr | typexpr typeconstr | ( typexpr {, typexpr} ) typeconstr | typexpr as ' ident | < [..] > | < method-type {; method-type} [; ..] > | # class-path | typexpr # class-path | ( typexpr {, typexpr}) # class-path method-type ::= method-name : typexpr The table below shows the relative precedences and associativity of operators and non-closed type constructions. The constructions with higher precedences come first. Chapter 4. The Objective Caml language 44 --------------------------------------------- |Operator |Associativity | --------------------------------------------- |Type constructor application |-- | |* |-- | |-> |right | --------------------------------------------- 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. 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. 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. 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. 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 the remaining part of the toplevel phrase. If the type variable ident actually occurs in typexpr, a recursive type is created. Recursive types are allowed as long as any recursion crosses a type constructor or an object type. Object types An object type < method-type {; method-type} > is a record of method types. 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 behaves as a type variable. Chapter 4. The Objective Caml language 45 #-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. 4.5 Constants constant ::= integer-literal | float-literal | char-literal | string-literal | cconstr The syntactic class of constants comprises literals from the four base types (integers, floating-point numbers, characters, character strings), and constant constructors. 4.6 Patterns pattern ::= value-name | _ | constant | pattern as value-name | ( pattern ) | ( pattern : typexpr ) | pattern | pattern | ncconstr pattern | pattern {, pattern} | { label = pattern {; label = pattern} } | [ pattern {; pattern} ] | pattern :: pattern The table below shows the relative precedences and associativity of operators and non-closed pattern constructions. The constructions with higher precedences come first. ---------------------------------------- |Operator |Associativity | ---------------------------------------- |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''. Chapter 4. The Objective Caml language 46 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 type. ``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 contain no identifiers. Hence no bindings are returned by matching against an ``or'' pattern. Variant patterns The pattern ncconstr pattern1 matches all variants whose constructor is equal to ncconstr, and whose argument matches pattern1. The pattern pattern1 :: pattern2 matches non-empty lists whose heads match pattern1, and whose tails match pattern2. This pattern behaves like ( :: ) ( pattern1 , pattern2 ). The pattern [ pattern1 ;...; patternn ] matches lists of length n whose elements match pattern1 ...patternn, respectively. This pattern behaves like pattern1 ::...:: patternn :: []. 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 { label1 = pattern1 ;...; labeln = patternn } matches records that define at least the labels label1 through labeln, and such that the Chapter 4. The Objective Caml language 47 value associated to labeli match the pattern patterni, for i= 1,...,n. The record value can define more labels than label1 ...labeln; the values associated to these extra labels are not taken into account for matching. 4.7 Expressions expr ::= value-path | constant | ( expr ) | begin expr end | ( expr : typexpr ) | expr , expr {, expr} | ncconstr expr | expr :: expr | [ expr {; expr} ] | [| expr {; expr} |] | { label = expr {; label = expr} } | expr expr | prefix-symbol expr | expr infix-op expr | expr . label | expr . label <- 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 [rec] let-binding {and let-binding} in expr | new class-path | expr # method-name | ( expr :> typexpr ) | ( expr : typexpr :> typexpr ) | {< inst-var-name = expr {; inst-var-name = expr} >} pattern-matching ::= pattern [when expr] -> expr {| pattern [when expr] -> expr} multiple-matching ::= {pattern}+ [when expr] -> expr let-binding ::= pattern = expr | value-name {pattern}+ [: typexpr] = expr infix-op ::= infix-symbol | * | = | or | & 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 *''. Chapter 4. The Objective Caml language 48 ---------------------------------------------------------------------- |Construction or operator |Associativity | ---------------------------------------------------------------------- |prefix-symbol |-- | |. .( .[ |-- | |function application |right | |constructor application |-- | |- -. (prefix) |-- | |**... |right | |*... /... %... mod |left | |+... -... |left | |:: |right | |@ ^ |right | |comparisons (= == < etc.), all other infix symbols|left | |not |-- | |& && |left | |or || |left | |, |-- | |<- := |right | |if |-- | |; |right | |let match fun function try |-- | ---------------------------------------------------------------------- 4.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 begin...end 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 : type ). This constraint forces the type of expr to be compatible with type. Parenthesized expressions can also contain coercions ( expr [: type] :> type ) (see subsection 4.7.5 below). Function application Function application is denoted by juxtaposition of expressions. The expression expr1 expr2...exprn evaluates the expressions expr1 to exprn. The expression expr1 must evaluate to a functional value, which is then applied to the values of expr2,...,exprn. The order in which the expressions expr1,...,exprn are evaluated is not specified. Chapter 4. The Objective Caml language 49 Function definition Two syntactic forms are provided to define functions. The first form is introduced by the keyword function: function pattern1 -> 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 pattern1...patternn -> expr This expression 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: function pattern1 [whencond1] -> expr1 | ... | patternn [whencondn] -> 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 and...and patternn = exprn in expr Chapter 4. The Objective Caml language 50 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 pattern1...patternm -> expr in a let expression, one may instead write let ident pattern1 ...patternm = expr Recursive definitions of names are introduced by let rec: let rec pattern1 = expr1 and...and 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 = fun...and...and namen = fun...in 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, 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. 4.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 (). Chapter 4. The Objective Caml language 51 Case expression The expression match expr with pattern1 -> 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 or 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 or expr2 behaves exactly as if expr1 then true else expr2. 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 while...done 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 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. 4.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 ncconstr expr evaluates to the variant value whose constructor is ncconstr, 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. Records The expression { label1 = expr1 ;...; labeln = exprn } evaluates to the record value { label1 = v1 ;...; labeln = vn }, where vi is the value of expri for i=1, ...,n. The labels label1 to labeln must all belong to the same record types; all labels 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 expr1 . label evaluates expr1 to a record value, and returns the value associated to label in this record value. The expression expr1 . label <- expr2 evaluates expr1 to a record value, which is then modified in-place by replacing the value associated to label in this record by the value of expr2. This operation is permitted only if label has been declared mutable in the definition of the record type. The whole expression expr1 . label <- expr2 evaluates to the unit value (). Chapter 4. The Objective Caml language 53 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 (). 4.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 14 for more details). Their meaning may be changed at any time using let ( infix-op ) name1 name2 =... Chapter 4. The Objective Caml language 54 ------------------------------------------------------------------------ |Operator |Initial meaning | ------------------------------------------------------------------------ |+ |Integer addition. | |- (infix) |Integer subtraction. | |- (prefix) |Integer negation. | |* |Integer multiplication. | |/ |Integer division. Raise Division_by_zero if second | | |argument is zero. The result is unspecified if either | | |argument is negative. | |mod |Integer modulus. Raise Division_by_zero if second | | |argument is zero. The result is unspecified if either | | |argument is negative. | |land |Bitwise logical ``and'' on integers. | |lor |Bitwise logical ``or on integers. | |lxor |Bitwise logical ``exclusive or'' on integers. | |lsl |Bitwise logical shift left on integers. | |lsr |Bitwise logical shift right on integers. | |asr |Bitwise 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'' | ------------------------------------------------------------------------ 4.7.5 Objects Object creation The expression new class-path denotes a function that takes some initialization arguments and returns a new object of class class-path. Message sending The expression expr # method-name invokes the method method-name of the object denoted by expr. Coercion The type of an object can be coerced (weakened) to a subtype. 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. It is more general than the previous one. Chapter 4. The Objective Caml language 55 Object duplication An object can be duplicated using the library function Oo.copy (see section 15.13). 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. 4.8 Type and exception definitions 4.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 labels associated with the definition. type-definition ::= type typedef {and typedef} typedef ::= [type-params] typeconstr-name [type-equation] [type-representation] type-equation ::= = typexpr type-representation ::= = constr-decl {| constr-decl} | = { label-decl {; label-decl} } type-params ::= ' ident | ( ' ident {, ' ident} ) constr-decl ::= cconstr-name | ncconstr-name of typexpr label-decl ::= label-name : typexpr | mutable label-name : 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. 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. These type parameters can appear in the type expressions of the right-hand side of the definition. 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 labels (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 ncconstr-name of typexpr declares the name ncconstr-name as a non-constant constructor, whose argument has type typexpr. The constructor declaration cconstr-name declares the name cconstr-name as a constant constructor. Chapter 4. The Objective Caml language 56 Constructor names must be capitalized. The type representation = { label-decl {; label-decl} } describes a record type. The label declarations label-decl1,...,label-decln describe the labels associated to this record type. The label declaration label-name : typexpr declares label-name as a label whose argument has type typexpr. The label declaration mutable label-name : typexpr behaves similarly; in addition, it allows physical modification over the argument to this label. 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 labels, 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 labels 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 labels, in the same order, with the same arguments. 4.8.2 Exception definitions exception-definition ::= exception constr-decl 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. Chapter 4. The Objective Caml language 57 4.9 Classes 4.9.1 Class definitions class-definition ::= class-header = {constraint} {class-fields} class-header ::= class-tags parameterized-class-name class-params class-binders class-tags ::= [virtual] [closed] parameterized-class-name ::= class-name | ' ident class-name | ( ' ident {, ' ident} ) class-name class-params ::= {pattern}+ class-binders ::= [as value-name] [: ' ident] constraint ::= constraint ' ident = typexpr class-fields ::= inherit ancestor | val value | virtual method-type | method method ancestor ::= [( typexpr {, typexpr} )] class-path {expr}+ [as value-name] value ::= [private] [mutable] inst-var-name [= expr] method ::= method-name {pattern} = expr method-type ::= method-name : typexpr Class definitions A class definition class class-definition {and class-definition} is recursive. Each class-definition 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. Type parameters A class class-name automatically defines two 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 4.4). The class type parameters correspond to the ones of these two abbreviations. They must be bound to actual types in the class definition using type constraints. The abbreviations are obtained by pruning the method types at all occurrences of a type parameter. So that the abbreviations are well-formed, no type variable must remain in the pruned types. Class parameters The parameters class-params are the ones of the object creation function new class-path, as well as the ones of the inheritance construct. Self and self type binders The binders class-binders, i.e. as value-name and : ' ident, allow to bind self (the current object) and its type, respectively. The variable value-name can then be used as any variable in method body. Constraints on type parameters The construct constraint ' ident = typexpr allows to specify type parameters. The value of the type parameter ident will be an instance of typexpr (more Chapter 4. The Objective Caml language 58 precisely, ident and typexpr are unified). Inheritance The inheritance construct inherit [( typexpr {, typexpr} )] class-path {expr}+ allows to reuse methods from other classes. It adds the instance variables and methods from class class-path into the current class, possibly overriding previously defined ones of the same name. Parent instance variables are initialized with parent class parameters bound to the arguments {expr}+. Parent type parameters are unified with type arguments typexpr1,...,typexprn. 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. Instance variable definition Instance variables can be defined or their status can be changed using the construct val value. The definition val [private] [mutable] inst-var-name = expr adds an instance variable inst-var-name whose initial value is the value of expression expr. If the variable was previously defined, its previous initial value is overridden. By default, this variable is visible in subclasses of current class. The flag private makes this variable only visible in the current class. The flag mutable allows physical modification of this variable by methods. The construct val [private] [mutable] inst-var-name enables to change the variable status (makes it private and/or mutable), while keeping the same initial value. Method definition Method definition is written method method. The definition of a method overrides any previous definition of this method. Method bodies do not have access to class parameters, but to instance variables. Some special expressions are available in method bodies for manipulating instance variables and duplicating self: expr ::= ... | inst-var-name | inst-var-name <- expr | {< [inst-var-name = expr {; inst-var-name = expr}] >} The expression inst-var-name evaluates to the value of the corresponding instance variable in the current object, while 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. Chapter 4. The Objective Caml language 59 Virtual class Methods can be declared, without being defined, with the construct virtual method-type. Methods that are declared in this way or applied to self but not actually defined are said to be virtual. A class must be flagged virtual if one of its methods is virtual. Objects cannot be created from a virtual class. Closed class A class can be flagged as closed. A closed class is a class to which subclasses cannot add methods. 4.9.2 Class types Class types are specifications for class definitions. The syntax of class types is closely modeled on class definitions. Some type information can be hidden in a class type: it can be given stronger constraints than a matched class; some instance variables can be omitted; some previously non-mutable instance variables can be flagged mutable. class-type ::= class-type-header = {constraint} {class-type-fields} class-type-header ::= class-tags parameterized-class-name class-type-params [: ' ident] class-type-params ::= {( typexpr )}+ class-type-fields ::= inherit ancestor-type | val value-type | virtual method-type | method method-type ancestor-type ::= [( typexpr {, typexpr} )] class-path value-type ::= [private] [mutable] inst-var-name [: typexpr] method-type ::= method-name : typexpr 4.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 constraint {and constraint} | ( module-type ) specification ::= val value-name : typexpr | external value-name : typexpr = external-declaration | type-definition | exception-definition | class class-type {and class-type} end | 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 constraint ::= type [type-parameters] typeconstr = typexp | module module-path = extended-module-path Chapter 4. The Objective Caml language 60 4.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. 4.10.2 Signatures Signatures are type specifications for structures. Signatures sig...end 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 13). 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 = typexp and an optional type representation = constr-decl... or = { label-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 labels 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 = typexp, no representation. The type name must be implemented by a type compatible with typexp. All users of the structure know that the type name is compatible with typexp. New variant type or record type: no equation, a representation. Chapter 4. The Objective Caml language 61 The type name must be implemented by a variant type or record type with exactly the constructors or labels specified. All users of the structure have access to the constructors or labels, 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 class specification is composed of one or several mutually recursive class types, as described in section 4.9.2. 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 ( name : module-type )...( name : module-type ) : module-type 1 1 n n 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 Chapter 4. The Objective Caml language 62 expression. 4.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). 4.10.4 The with operator Assuming module-type denotes a signature, the expression module-type with constraint {and 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 = typexp adds the type equation = typexp 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) ... 4.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. Chapter 4. The Objective Caml language 63 module-expr ::= module-path | struct {definition [;;]} end | functor ( module-name : module-type ) -> module-expr | module-expr ( module-expr ) | ( module-expr ) | ( module-expr : module-type ) definition ::= let [rec] let-binding {and let-binding} | external value-name : typexpr = external-declaration | type-definition | exception-definition | class class-definition {and class-definition} end | module module-name {( module-name : module-type )} [: module-type] = module-expr | module type modtype-name = module-type | open module-path 4.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. 4.11.2 Structures Structures struct...end 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 7) 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. Value definitions A value definition let [rec] let-binding {and let-binding} bind value names in the same way as a let...in... expression (see section 4.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 13). Type definitions A definition of one or several type components is written type typedef {and typedef} and consists of a sequence of mutually recursive Chapter 4. The Objective Caml language 64 definitions of type names. Exception definitions Exceptions are defined with the syntax exception constr-decl. Class definitions The class keyword introduces one or several mutually recursive class definitions, as described in section 4.9.1. 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 ( name : module-type )...( name : module-type ) = module-expr 1 1 n n 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. 4.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). Chapter 4. The Objective Caml language 65 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. 4.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 sig...end signature expression. The implementation contains a sequence of definitions, just as the inside of a struct...end 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 6 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 interface1 end...namen : sig interfacen end where name1...nameN are the names of the other compilation units available in the search path (see chapter 6 for more details) and interface1...interfacen are their respective interfaces. Chapter 5 Language extensions This chapter describes the language features that are implemented in Objective Caml, but not described in the Objective Caml reference manual. In contrast with the fairly stable kernel language that is described in the reference manual, the extensions presented here are still experimental, and may be removed or changed in the future. 5.1 Streams and stream parsers Objective Caml comprises a library type for streams (possibly infinite sequences of elements, that are evaluated on demand), and associated stream expressions, to build streams, and stream patterns, to destructure streams. Streams and stream patterns provide a natural approach to the writing of recursive-descent parsers. Streams are presented by the following extensions to the syntactic classes of expressions: expr ::= ... | [< >] | [< stream-component {; stream-component} >] | parser [pattern] stream-matching | match expr with parser [pattern] stream-matching stream-component ::= ' expr | expr stream-matching ::= stream-pattern [pattern] -> expr {| stream-pattern [pattern] -> expr} stream-pattern ::= [< >] | [< stream-pat-comp {; stream-pat-comp [? expr]} >] stream-pat-comp ::= ' pattern [when expr] | pattern = expr | ident Stream expressions are bracketed by [< and >]. They represent the concatenation of their components. The component ' expr represents the one-element stream whose element is the value of expr. The component expr represents a sub-stream. For instance, if both s and t are streams of integers, then [<'1; s; t; '2>] is a stream of integers containing the element 1, then the elements of s, then those of t, and finally 2. The empty stream is denoted by [< >]. Unlike any other kind of expressions in the language, stream expressions are submitted to lazy evaluation: the components are not evaluated when the stream is built, but only when they are accessed during stream matching. The components are evaluated once, the first time they are accessed; the following 66 Chapter 5. Language extensions 67 accesses reuse the value computed the first time. Stream patterns, also bracketed by [< and >], describe initial segments of streams. In particular, the stream pattern [< >] matches all streams. Stream pattern components are matched against the corresponding elements of a stream. The component ' pattern matches the corresponding stream element against the pattern; if followed by when, the match is accepted only if the result of the guard expression is true. The component pattern = expr applies the function denoted by expr to the current stream, then matches the result of the function against pattern. Finally, the component ident simply binds the identifier to the stream being matched. Stream matching proceeds destructively: once a component has been matched, it is discarded from the stream (by in-place modification). Stream matching proceeds in two steps: first, a pattern is selected by matching the stream against the first components of the stream patterns; then, the following components of the selected pattern are checked against the stream. If the following components do not match, the exception Stream.Parse_error is raised. There is no backtracking here: stream matching commits to the pattern selected according to the first element. If none of the first components of the stream patterns match, the exception Stream.Parse_failure is raised. The Stream.Parse_failure exception causes the next alternative to be tried, if it occurs during the matching of the first element of a stream, before matching has committed to one pattern. The streams hold the count of their elements discarded. The optional pattern before the first stream pattern is bound to the stream count before the matching. The one after each stream pattern (optional, too) is bound to the stream count after the matching. The exception Parse_error has a string parameter coming from the optional ? expr after the stream pattern components (its default is the empty string). This expression is evaluated only in case of error. See Functional programming using Caml Light for a more gentle introductions to streams, and for some examples of their use in writing parsers. A more formal presentation of streams, and a discussion of alternate semantics, can be found in Parsers in ML by Michel Mauny and Daniel de Rauglaudre, in the proceedings of the 1992 ACM conference on Lisp and Functional Programming. 5.2 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. Part III The Objective Caml tools 68 Chapter 6 Batch compilation (ocamlc) This chapter describes the Objective Caml batch compiler ocamlc, which compiles Caml source files to bytecode object files and link these object files to produce standalone bytecode executable files. These executable files are then run by the bytecode interpreter ocamlrun. 6.1 Overview of the compiler The ocamlc command has a command-line interface similar to the one of most C compilers. It accepts several types of arguments: - Arguments ending in .mli are taken to be source files for compilation unit interfaces. Interfaces specify the names exported by compilation units: they declare value names with their types, define public data types, declare abstract data types, and so on. From the file x.mli, the ocamlc compiler produces a compiled interface in the file x.cmi. - Arguments ending in .ml are taken to be source files for compilation unit implementations. Implementations provide definitions for the names exported by the unit, and also contain expressions to be evaluated for their side-effects. From the file x.ml, the ocamlc compiler produces compiled object bytecode in the file x.cmo. If the interface file x.mli exists, the implementation x.ml is checked against the corresponding compiled interface x.cmi, which is assumed to exist. If no interface x.mli is provided, the compilation of x.ml produces a compiled interface file x.cmi in addition to the compiled object code file x.cmo. The file x.cmi produced corresponds to an interface that exports everything that is defined in the implementation x.ml. - Arguments ending in .cmo are taken to be compiled object bytecode. These files are linked together, along with the object files obtained by compiling .ml arguments (if any), and the Caml Light standard library, to produce a standalone executable program. The order in which .cmo and .ml arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given x.cmo file must come before all .cmo files that refer to the unit x. - Arguments ending in .cma are taken to be libraries of object bytecode. A library of object bytecode packs in a single file a set of object 69 Chapter 6. Batch compilation (ocamlc) 70 bytecode files (.cmo files). Libraries are built with ocamlc -a (see the description of the -a option below). The object files contained in the library are linked as regular .cmo files (see above), in the order specified when the .cma file was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in. - Arguments ending in .c are passed to the C compiler, which generates a .o object file. This object file is linked with the program if the -custom flag is set (see the description of -custom below). - Arguments ending in .o or .a are assumed to be C object files and libraries. They are passed to the C linker when linking in -custom mode (see the description of -custom below). The output of the linking phase is a file containing compiled bytecode that can be executed by the Objective Caml bytecode interpreter: the command named ocamlrun. If caml.out is the name of the file produced by the linking phase, the command ocamlrun caml.out arg1 arg2 ... argn executes the compiled code contained in caml.out, passing it as arguments the character strings arg1 to argn. (See chapter 8 for more details.) On most Unix systems, the file produced by the linking phase can be run directly, as in: ./caml.out arg1 arg2 ... argn The produced file has the executable bit set, and it manages to launch the bytecode interpreter by itself. 6.2 Options The following command-line options are recognized by ocamlc. -a Build a library (.cma file) with the object files (.cmo files) given on the command line, instead of linking them into an executable file. The name of the library can be set with the -o option. The default name is library.cma. -c Compile only. Suppress the linking phase of the compilation. Source code files are turned into compiled files, but no executable file is produced. This option is useful to compile modules separately. -cclib -llibname Pass the -llibname option to the C linker when linking in ``custom runtime'' mode (see the -custom option). This causes the given C library to be linked with the program. -ccopt option Pass the given option to the C compiler and linker, when linking in ``custom runtime'' mode (see the -custom option). For instance, -ccopt -Ldir causes the C linker to search for C libraries in directory dir. -custom Link in ``custom runtime'' mode. In the default linking mode, the linker Chapter 6. Batch compilation (ocamlc) 71 produces bytecode that is intended to be executed with the shared runtime system, ocamlrun. In the custom runtime mode, the linker produces an output file that contains both the runtime system and the bytecode for the program. The resulting file is larger, but it can be executed directly, even if the ocamlrun command is not installed. Moreover, the ``custom runtime'' mode enables linking Caml code with user-defined C functions, as described in chapter 13. -i Cause the compiler to print all defined names (with their inferred types or their definitions) when compiling an implementation (.ml file). This can be useful to check the types inferred by the compiler. Also, since the output follows the syntax of interfaces, it can help in writing an explicit interface (.mli file) for a file: just redirect the standard output of the compiler to a .mli file, and edit that file to remove all declarations of unexported names. -I directory Add the given directory to the list of directories searched for compiled interface files (.cmi) and compiled object code files (.cmo). By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. -impl filename Compile the file filename as an implementation file, even if its extension is not .ml. -intf filename Compile the file filename as an interface file, even if its extension is not .mli. -linkall Forces all modules contained in libraries to be linked in. If this flag is not given, unreferenced modules are not linked in. When building a library (-a flag), setting the -linkall flag forces all subsequent links of programs involving that library to link all the modules contained in the library. -o exec-file Specify the name of the output file produced by the linker. The default output name is a.out, in keeping with the Unix tradition. If the -a option is given, specify the name of the library produced. -pp command Cause the compiler to call the given command as a preprocessor for each source file. The output of command is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards. The name of this file is built from the basename of the source file with the extension .ppi for an interface (.mli) file and .ppo for an implementation (.ml) file. -thread Compile or link multithreaded programs, in combination with the [Threads] library described in chapter 19. What this option actually does is select a special, thread-safe version of the standard library. -v Print the version number of the compiler. Chapter 6. Batch compilation (ocamlc) 72 -unsafe Turn bound checking off on array and string accesses (the v.(i) and s.[i] constructs). Programs compiled with -unsafe are therefore slightly faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. 6.3 Modules and the file system This short section is intended to clarify the relationship between the names of the modules corresponding to compilation units and the names of the files that contain their compiled interface and compiled implementation. The compiler always derives the module name by taking the capitalized base name of the source file (.ml or .mli file). That is, it strips the leading directory name, if any, as well as the .ml or .mli suffix; then, it set the first letter to uppercase, in order to comply with the requirement that module names must be capitalized. For instance, compiling the file mylib/misc.ml provides an implementation for the module named Misc. Other compilation units may refer to components defined in mylib/misc.ml under the names Misc.name; they can also do open Misc, then use unqualified names name. The .cmi and .cmo files produced by the compiler have the same base name as the source file. Hence, the compiled files always have their base name equal (modulo capitalization of the first letter) to the name of the module they describe (for .cmi files) or implement (for .cmo files). When the compiler encounters a reference to a free module identifier Mod, it looks in the search path for a file mod.cmi (note lowercasing of first letter) and loads the compiled interface contained in that file. As a consequence, renaming .cmi files is not advised: the name of a .cmi file must always correspond to the name of the compilation unit it implements. It is admissible to move them to another directory, if their base name is preserved, and the correct -I options are given to the compiler. The compiler will flag an error if it loads a .cmi file that has been renamed. Compiled bytecode files (.cmo files), on the other hand, can be freely renamed once created. That's because the linker never attempts to find by itself the .cmo file that implements a module with a given name: it relies instead on the user providing the list of .cmo files by hand. 6.4 Common errors This section describes and explains the most frequently encountered error messages. Cannot find file filename The named file could not be found in the current directory, nor in the directories of the search path. The filename is either a compiled interface file (.cmi file), or a compiled bytecode file (.cmo file). If filename has the format mod.cmi, this means you are trying to compile a file that references identifiers from module mod, but you have not yet compiled an interface for module mod. Fix: compile mod.mli or mod.ml first, to create the compiled interface mod.cmi. If filename has the format mod.cmo, this means you are trying to link a bytecode object file that does not exist yet. Fix: compile mod.ml first. If your program spans several directories, this error can also appear because you haven't specified the directories to look into. Fix: add the correct -I options to the command line. Chapter 6. Batch compilation (ocamlc) 73 Corrupted compiled interface filename The compiler produces this error when it tries to read a compiled interface file (.cmi file) that has the wrong structure. This means something went wrong when this .cmi file was written: the disk was full, the compiler was interrupted in the middle of the file creation, and so on. This error can also appear if a .cmi file is modified after its creation by the compiler. Fix: remove the corrupted .cmi file, and rebuild it. This expression has type t1, but is used with type t2 This is by far the most common type error in programs. Type t1 is the type inferred for the expression (the part of the program that is displayed in the error message), by looking at the expression itself. Type t2 is the type expected by the context of the expression; it is deduced by looking at how the value of this expression is used in the rest of the program. If the two types t1 and t2 are not compatible, then the error above is produced. In some cases, it is hard to understand why the two types t1 and t2 are incompatible. For instance, the compiler can report that ``expression of type foo cannot be used with type foo'', and it really seems that the two types foo are compatible. This is not always true. Two type constructors can have the same name, but actually represent different types. This can happen if a type constructor is redefined. Example: type foo = A | B let f = function A -> 0 | B -> 1 type foo = C | D f C This result in the error message ``expression C of type foo cannot be used with type foo''. The type of this expression, t, contains type variables that cannot be generalized Type variables ('a, 'b, ...) in a type t can be in either of two states: generalized (which means that the type t is valid for all possible instantiations of the variables) and not generalized (which means that the type t is valid only for one instantiation of the variables). In a let binding let name = expr, the type-checker normally generalizes as many type variables as possible in the type of expr. However, this leads to unsoundness (a well-typed program can crash) in conjunction with polymorphic mutable data structures. To avoid this, generalization is performed at let bindings only if the bound expression expr belongs to the class of ``syntactic values'', which includes constants, identifiers, functions, tuples of syntactic values, etc. In all other cases (for instance, expr is a function application), a polymorphic mutable could have been created and generalization is therefore turned off. Non-generalized type variables in a type cause no difficulties inside a given structure or compilation unit (the contents of a .ml file, or an interactive session), but they cannot be allowed inside signatures nor in compiled interfaces (.cmi file), because they could be used inconsistently later. Therefore, the compiler flags an error when a structure or compilation unit defines a value name whose type contains Chapter 6. Batch compilation (ocamlc) 74 non-generalized type variables. There are two ways to fix this error: - Add a type constraint or a .mli file to give a monomorphic type (without type variables) to name. For instance, instead of writing let sort_int_list = Sort.list (<) (* inferred type 'a list -> 'a list, with 'a not generalized *) write let sort_int_list = (Sort.list (<) : int list -> int list);; - If you really need name to have a polymorphic type, turn its defining expression into a function by adding an extra parameter. For instance, instead of writing let map_length = List.map Array.length (* inferred type 'a array list -> int list, with 'a not general- ized *) write let map_length lv = List.map Array.length lv Reference to undefined global mod This error appears when trying to link an incomplete or incorrectly ordered set of files. Either you have forgotten to provide an implementation for the compilation unit named mod on the command line (typically, the file named mod.cmo, or a library containing that file). Fix: add the missing .ml or .cmo file to the command line. Or, you have provided an implementation for the module named mod, but it comes too late on the command line: the implementation of mod must come before all bytecode object files that reference mod. Fix: change the order of .ml and .cmo files on the command line. Of course, you will always encounter this error if you have mutually recursive functions across modules. That is, function Mod1.f calls function Mod2.g, and function Mod2.g calls function Mod1.f. In this case, no matter what permutations you perform on the command line, the program will be rejected at link-time. Fixes: - Put f and g in the same module. - Parameterize one function by the other. That is, instead of having mod1.ml: let f x = ... Mod2.g ... mod2.ml: let g y = ... Mod1.f ... Chapter 6. Batch compilation (ocamlc) 75 define mod1.ml: let f g x = ... g ... mod2.ml: let rec g y = ... Mod1.f g ... and link mod1.cmo before mod2.cmo. - Use a reference to hold one of the two functions, as in : mod1.ml: let forward_g = ref((fun x -> failwith "forward_g") : ) let f x = ... !forward_g ... mod2.ml: let g y = ... Mod1.f ... Mod1.forward_g := g This will not work if g is a polymorphic function, however. The external function f is not available This error appears when trying to link code that calls external functions written in C in ``default runtime'' mode. As explained in chapter 13, such code must be linked in ``custom runtime'' mode. Fix: add the -custom option, as well as the C libraries and C object files that implement the required external functions. Chapter 7 The toplevel system (ocaml) This chapter describes the toplevel system for Objective Caml, that permits interactive use of the Objective Caml system through a read-eval-print loop. In this mode, the system repeatedly reads Caml phrases from the input, then typechecks, compile and evaluate them, then prints the inferred type and result value, if any. The system prints a # (sharp) prompt before reading each phrase. A toplevel phrase can span several lines. It is terminated by ;; (a double-semicolon). The syntax of toplevel phrases is as follows: toplevel-phrase ::= definition ;; | expr ;; | # ident directive-argument ;; definition ::= let [rec] let-binding {and let-binding} | external value-name : typexpr = external-declaration | type-definition | exception-definition | module module-name [: module-type] = module-expr | module type modtype-name = module-type | open module-path directive-argument ::= nothing | string-literal | integer-literal | value-path A phrase can consist of a definition, similar to those found in implementations of compilation units or in struct...end module expressions. The definition can bind value names, type names, an exception, a module name, or a module type name. The toplevel system performs the bindings, then prints the types and values (if any) for the names thus defined. A phrase may also consist in a open directive (see section 4.11), or a value expression (section 4.7). Expressions are simply evaluated, without performing any bindings, and the value of the expression is printed. Finally, a phrase can also consist in a toplevel directive, starting with # (the sharp sign). These directives control the behavior of the toplevel; they are listed below in section 7.2. Unix: The toplevel system is started by the command ocaml. Phrases are read on standard input, results are printed on standard output, errors on standard error. End-of-file on standard input terminates ocaml (see also the #quit directive in section 7.2). 76 Chapter 7. The toplevel system (ocaml) 77 The toplevel system does not perform line editing, but it can easily be used in conjunction with an external line editor such as fep; just run fep -emacs ocaml or fep -vi ocaml. Another option is to use ocaml under Gnu Emacs, which gives the full editing power of Emacs (see the camlmode package distributed with Caml Light 0.7). At any point, the parsing, compilation or evaluation of the current phrase can be interrupted by pressing ctrl-C (or, more precisely, by sending the intr signal to the ocaml process). The toplevel then immediately returns to the # prompt. Windows: In addition to the text-only command ocaml.exe, which works exactly as under Unix (see above), a graphical user interface for the toplevel is available under the name ocamlwin.exe. It should be launched from the Windows file manager or program manager. The ``Terminal'' windows is split in two panes. Phrases are entered and edited in the bottom pane. The top pane displays a copy of the input phrases as they are processed by the Caml Light toplevel, interspersed with the toplevel responses. The ``Return'' key sends the contents of the bottom pane to the Caml Light toplevel. The ``Enter'' key inserts a newline without sending the contents of the Input window. (This can be configured with the ``Preferences'' menu item.) The contents of the input window can be edited at all times, with the standard Windows interface. An history of previously entered phrases is maintained and displayed in a separate window. To quit the Camlwin application, either select ``Quit'' from the ``File'' menu, or use the quit function described below. At any point, the parsing, compilation or evaluation of the current phrase can be interrupted by selecting the ``Interrupt Caml Light'' menu item. This goes back to the # prompt. 7.1 Options The following command-line options are recognized by the ocaml command. -I directory Add the given directory to the list of directories searched for source and compiled files. By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. Directories can also be added to the search path once the toplevel is running with the #directory directive (section 7.2). -unsafe See the corresponding option for ocamlc, chapter 6. Turn bound checking off on array and string accesses (the v.(i) and s.[i] constructs). Programs compiled with -unsafe are therefore slightly faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. Chapter 7. The toplevel system (ocaml) 78 The following environment variables are also consulted: LC_CTYPE If set to iso_8859_1, accented characters (from the ISO Latin-1 character set) in string and character literals are printed as is; otherwise, they are printed as decimal escape sequences (\ddd). TERM When printing error messages, the toplevel system attempts to underline visually the location of the error. It consults the TERM variable to determines the type of output terminal and look up its capabilities in the terminal database. 7.2 Toplevel directives The following directives control the toplevel behavior, load files in memory, and trace program execution. #quit;; Exit the toplevel loop and terminate the ocaml command. #directory "dir-name";; Add the given directory to the list of directories searched for source and compiled files. #cd "dir-name";; Change the current working directory. #load "file-name";; Load in memory a bytecode object file (.cmo file) produced by the batch compiler ocamlc. #use "file-name";; Read, compile and execute source phrases from the given file. This is textual inclusion: phrases are processed just as if they were typed on standard input. The reading of the file stops at the first error encountered. #install_printer printer-name;; This directive registers the function named printer-name (a value path) as a printer for objects whose types match the argument type of the function. That is, the toplevel loop will call printer-name when it has such an object to print. The printing function printer-name must use the Format library module to produce its output, otherwise its output will not be correctly located in the values printed by the toplevel loop. #remove_printer printer-name;; Remove the named function from the table of toplevel printers. #trace function-name;; After executing this directive, all calls to the function named function-name will be ``traced''. That is, the argument and the result are displayed for each call, as well as the exceptions escaping out of the function, raised either by the function itself or by another function it calls. If the function is curried, each argument is printed as it is passed to the function. Chapter 7. The toplevel system (ocaml) 79 #untrace function-name;; Stop tracing the given function. #untrace_all;; Stop tracing all functions traced so far. #print_depth n;; Limit the printing of values to a maximal depth of n. The parts of values whose depth exceeds n are printed as ... (ellipsis). #print_length n;; Limit the number of value nodes printed to at most n. Remaining parts of values are printed as ... (ellipsis). 7.3 The toplevel and the module system Toplevel phrases can refer to identifiers defined in compilation units with the same mechanisms as for separately compiled units: either by using qualified names (modulename.localname), or by using the open construct and unqualified names (see section 4.3). However, before referencing another compilation unit, an implementation of that unit must be present in memory. At start-up, the toplevel system contains implementations for all the modules in the the standard library. Implementations for user modules can be entered with the #load directive described above. Referencing a unit for which no implementation has been provided results in the error ``Reference to undefined global `...'''. Note that entering open mod merely accesses the compiled interface (.cmi file) for mod, but does not load the implementation of mod, and does not cause any error if no implementation of mod has been loaded. The error ``reference to undefined global mod'' will occur only when executing a value or module definition that refers to mod. 7.4 Common errors This section describes and explains the most frequently encountered error messages. Cannot find file filename The named file could not be found in the current directory, nor in the directories of the search path. If filename has the format mod.cmi, this means you have referenced the compilation unit mod, but its compiled interface could not be found. Fix: compile mod.mli or mod.ml first, to create the compiled interface mod.cmi. If filename has the format mod.cmo, this means you are trying to load with #load a bytecode object file that does not exist yet. Fix: compile mod.ml first. If your program spans several directories, this error can also appear because you haven't specified the directories to look into. Fix: use the #directory directive to add the correct directories to the search path. This expression has type t1, but is used with type t2 See section 6.4. Chapter 7. The toplevel system (ocaml) 80 Reference to undefined global mod You have neglected to load in memory an implementation for a module with #load. See section 7.3 above. 7.5 Building custom toplevel systems: ocamlmktop The ocamlmktop command builds Objective Caml toplevels that contain user code preloaded at start-up. The ocamlmktop command takes as argument a set of .cmo and .cma files, and links them with the object files that implement the Objective Caml toplevel. The typical use is: ocamlmktop -o mytoplevel foo.cmo bar.cmo gee.cmo This creates the bytecode file mytoplevel, containing the Objective Caml toplevel system, plus the code from the three .cmo files. This toplevel is directly executable and is started by: ./mytoplevel This enters a regular toplevel loop, except that the code from foo.cmo, bar.cmo and gee.cmo is already loaded in memory, just as if you had typed: #load "foo.cmo";; #load "bar.cmo";; #load "gee.cmo";; on entrance to the toplevel. The modules Foo, Bar and Gee are not opened, though; you still have to do open Foo;; yourself, if this is what you wish. 7.6 Options The following command-line options are recognized by ocamlmktop. -cclib libname Pass the -llibname option to the C linker when linking in ``custom runtime'' mode. See the corresponding option for ocamlc, in chapter 6. -ccopt option Pass the given option to the C compiler and linker, when linking in ``custom runtime'' mode. See the corresponding option for ocamlc, in chapter 6. -custom Link in ``custom runtime'' mode. See the corresponding option for ocamlc, in chapter 6. -I directory Add the given directory to the list of directories searched for compiled object code files (.cmo and .cma). -o exec-file Specify the name of the toplevel file produced by the linker. The Chapter 7. The toplevel system (ocaml) 81 default is a.out. Chapter 8 The runtime system (ocamlrun) The ocamlrun command executes bytecode files produced by the linking phase of the ocamlc command. 8.1 Overview The ocamlrun command comprises three main parts: the bytecode interpreter, that actually executes bytecode files; the memory allocator and garbage collector; and a set of C functions that implement primitive operations such as input/output. The usage for ocamlrun is: ocamlrun options bytecode-executable arg1 ... argn The first non-option argument is taken to be the name of the file containing the executable bytecode. (That file is searched in the executable path as well as in the current directory.) The remaining arguments are passed to the Caml Light program, in the string array Sys.argv. Element 0 of this array is the name of the bytecode executable file; elements 1 to n are the remaining arguments arg1 to argn. As mentioned in chapter 6, in most cases, the bytecode executable files produced by the ocamlc command are self-executable, and manage to launch the ocamlrun command on themselves automatically. That is, assuming caml.out is a bytecode executable file, caml.out arg1 ... argn works exactly as ocamlrun caml.out arg1 ... argn Notice that it is not possible to pass options to ocamlrun when invoking caml.out directly. 8.2 Options The following command-line option is recognized by ocamlrun. -v When set, the memory manager prints verbose messages on standard error to signal garbage collections and heap extensions. The following environment variable are also consulted: 82 Chapter 8. The runtime system (ocamlrun) 83 CAMLRUNPARAM Set the garbage collection parameters. This variable must be a sequence of parameter specifications. A parameter specification is an option letter followed by an = sign and a decimal number. There are four options, corresponding to the four fields of the control record documented in section 15.7: s (minor_heap_size) Size of the minor heap. i (major_heap_increment) Minimum size increment for the major heap. o (space_overhead) The major GC speed setting. v (verbose) Whether to print GC messages or not. 0 is false; 1 is true; other values may give unexpected results. For example, under csh the command setenv CAMLRUNPARAM 's=250000 v=1' tells a subsequent ocamlrun to set its initial minor heap size to about 1 megabyte (on a 32-bit machine) and to print its GC messages. PATH List of directories searched to find the bytecode executable file. 8.3 Common errors This section describes and explains the most frequently encountered error messages. filename: no such file or directory If filename is the name of a self-executable bytecode file, this means that either that file does not exist, or that it failed to run the ocamlrun bytecode interpreter on itself. The second possibility indicates that Objective Caml has not been properly installed on your system. Cannot exec camlrun (When launching a self-executable bytecode file.) The ocamlrun could not be found in the executable path. Check that Objective Caml has been properly installed on your system. Cannot find the bytecode file The file that ocamlrun is trying to execute (e.g. the file given as first non-option argument to ocamlrun) either does not exist, or is not a valid executable bytecode file. Truncated bytecode file The file that ocamlrun is trying to execute is not a valid executable bytecode file. Probably it has been truncated or mangled since created. Erase and rebuild it. Chapter 8. The runtime system (ocamlrun) 84 Uncaught exception The program being executed contains a ``stray'' exception. That is, it raises an exception at some point, and this exception is never caught. This causes immediate termination of the program. The name of the exception is printed, but not its arguments. Out of memory The program being executed requires more memory than available. Either the program builds excessively large data structures; or the program contains too many nested function calls, and the stack overflows. In some cases, your program is perfectly correct, it just requires more memory than your machine provides. In other cases, the ``out of memory'' message reveals an error in your program: non-terminating recursive function, allocation of an excessively large array or string, attempts to build an infinite list or other data structure, ... To help you diagnose this error, run your program with the -v option to ocamlrun. If it displays lots of ``Growing stack...'' messages, this is probably a looping recursive function. If it displays lots of ``Growing heap...'' messages, with the heap size growing slowly, this is probably an attempt to construct a data structure with too many (infinitely many?) cells. If it displays few ``Growing heap...'' messages, but with a huge increment in the heap size, this is probably an attempt to build an excessively large array or string. Chapter 9 Native-code compilation (ocamlopt) This chapter describes the Objective Caml high-performance native-code compiler ocamlopt, which compiles Caml source files to native code object files and link these object files to produce standalone executables. The native-code compiler is only available on certain platforms. It produces code that runs faster than the bytecode produced by ocamlc, at the cost of increased compilation time and executable code size. Compatibility with the bytecode compiler is extremely high: the same source code should run identically when compiled with ocamlc and ocamlopt. It is not possible to mix native-code object files produced by ocamlc with bytecode object files produced by ocamlopt: a program must be compiled entirely with ocamlopt or entirely with ocamlc. Native-code object files produced by ocamlopt cannot be loaded in the toplevel system ocaml. 9.1 Overview of the compiler The ocamlopt command has a command-line interface very close to that of ocamlc. It accepts the same types of arguments: - Arguments ending in .mli are taken to be source files for compilation unit interfaces. Interfaces specify the names exported by compilation units: they declare value names with their types, define public data types, declare abstract data types, and so on. From the file x.mli, the ocamlopt compiler produces a compiled interface in the file x.cmi. The interface produced is identical to that produced by the bytecode compiler ocamlc. - Arguments ending in .ml are taken to be source files for compilation unit implementations. Implementations provide definitions for the names exported by the unit, and also contain expressions to be evaluated for their side-effects. From the file x.ml, the ocamlopt compiler produces two files: x.o, containing native object code, and x.cmx, containing extra information for linking and optimization of the clients of the unit. The compiled implementation should always be referred to under the name x.cmx (when given a .o file, ocamlopt assumes that it contains code compiled from C, not from Caml). The implementation is checked against the interface file x.mli (if it exists) as described in the manual for ocamlc (chapter 6). - Arguments ending in .cmx are taken to be compiled object code. These files are linked together, along with the object files obtained by compiling .ml arguments (if any), and the Caml Light standard library, to 85 Chapter 9. Native-code compilation (ocamlopt) 86 produce a native-code executable program. The order in which .cmx and .ml arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given x.cmx file must come before all .cmx files that refer to the unit x. - Arguments ending in .cmxa are taken to be libraries of object code. Such a library packs in two files (lib.cmxa and lib.a) a set of object files (.cmx/.o files). Libraries are build with ocamlopt -a (see the description of the -a option below). The object files contained in the library are linked as regular .cmx files (see above), in the order specified when the library was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in. - Arguments ending in .c are passed to the C compiler, which generates a .o object file. This object file is linked with the program. - Arguments ending in .o or .a are assumed to be C object files and libraries. They are linked with the program. The output of the linking phase is a regular Unix executable file. It does not need ocamlrun to run. 9.2 Options The following command-line options are recognized by ocamlopt. -a Build a library (.cmxa/.a file) with the object files (.cmx/.o files) given on the command line, instead of linking them into an executable file. The name of the library can be set with the -o option. The default name is library.cmxa. -c Compile only. Suppress the linking phase of the compilation. Source code files are turned into compiled files, but no executable file is produced. This option is useful to compile modules separately. -cclib -llibname Pass the -llibname option to the linker. This causes the given C library to be linked with the program. -ccopt option Pass the given option to the C compiler and linker. For instance, -ccopt -Ldir causes the C linker to search for C libraries in directory dir. -compact Optimize the produced code for space rather than for time. This results in slightly smaller but slightly slower programs. The default is to optimize for speed. -i Cause the compiler to print all defined names (with their inferred types or their definitions) when compiling an implementation (.ml file). This can be useful to check the types inferred by the compiler. Also, since the output follows the syntax of interfaces, it can help in writing an explicit interface (.mli file) for a file: just redirect the standard output of the compiler to a .mli file, and edit that file to remove all Chapter 9. Native-code compilation (ocamlopt) 87 declarations of unexported names. -I directory Add the given directory to the list of directories searched for compiled interface files (.cmi) and compiled object code files (.cmx). By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. -linkall Forces all modules contained in libraries to be linked in. If this flag is not given, unreferenced modules are not linked in. When building a library (-a flag), setting the -linkall flag forces all subsequent links of programs involving that library to link all the modules contained in the library. -o exec-file Specify the name of the output file produced by the linker. The default output name is a.out, in keeping with the Unix tradition. If the -a option is given, specify the name of the library produced. -pp command Cause the compiler to call the given command as a preprocessor for each source file. The output of command is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards. The name of this file is built from the basename of the source file with the extension .ppi for an interface (.mli) file and .ppo for an implementation (.ml) file. -S Keep the assembly code produced during the compilation. The assembly code for the source file x.ml is saved in the file x.s. -v Print the version number of the compiler. -unsafe Turn bound checking off on array and string accesses (the v.(i) and s.[i] constructs). Programs compiled with -unsafe are therefore faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. 9.3 Common errors The error messages are almost identical to those of ocamlc. See section 6.4. 9.4 Compatibility with the bytecode compiler This section lists the known incompatibilities between the bytecode compiler and the native-code compiler. Except on those points, the two compilers should generate code that behave identically. - The following operations abort the program (often via an hardware trap) instead of raising an exception (Invalid_argument and Division_by_zero respectively): - accesses to arrays and strings out of bounds; Chapter 9. Native-code compilation (ocamlopt) 88 - integer division by zero, modulus by zero; - on the Alpha processor only, floating-point operations involving infinite or denormalized numbers (all other processors supported by ocamlopt treat these numbers correctly, as per the IEEE 754 standard). - The following library functions print a fatal error message and abort the program instead of raising the Invalid_argument exception: - structural comparisons (=), (<>), etc., when encountering a functional value; - Array.create and String.create when the requested size is negative or exceeds the memory manager limits; - output_value when encountering a functional value or pointers outside the Caml heap (such as input-output buffers). - Signals are detected only when the program performs an allocation in the heap. That is, if a signal is delivered while in a piece of code that does not allocate, its handler will not be called until the next heap allocation. Chapter 10 Lexer and parser generators (ocamllex, ocamlyacc) This chapter describes two program generators: ocamllex, that produces a lexical analyzer from a set of regular expressions with associated semantic actions, and ocamlyacc, that produces a parser from a grammar with associated semantic actions. These program generators are very close to the well-known lex and yacc commands that can be found in most C programming environments. This chapter assumes a working knowledge of lex and yacc: while it describes the input syntax for ocamllex and ocamlyacc and the main differences with lex and yacc, it does not explain the basics of writing a lexer or parser description in lex and yacc. Readers unfamiliar with lex and yacc are referred to ``Compilers: principles, techniques, and tools'' by Aho, Sethi and Ullman (Addison-Wesley, 1986), ``Compiler design in C'' by Holub (Prentice-Hall, 1990), or ``Lex & Yacc'', by Mason and Brown (O'Reilly, 1990). 10.1 Overview of ocamllex The ocamllex command produces a lexical analyzer from a set of regular expressions with attached semantic actions, in the style of lex. Assuming the input file is lexer.mll, executing ocamllex lexer.mll produces Caml code for a lexical analyzer in file lexer.ml. This file defines one lexing function per entry point in the lexer definition. These functions have the same names as the entry points. Lexing functions take as argument a lexer buffer, and return the semantic attribute of the corresponding entry point. Lexer buffers are an abstract data type implemented in the standard library module Lexing. The functions Lexing.from_channel, Lexing.from_string and Lexing.from_function create lexer buffers that read from an input channel, a character string, or any reading function, respectively. (See the description of module Lexing in chapter 14.) When used in conjunction with a parser generated by ocamlyacc, the semantic actions compute a value belonging to the type token defined by the generated parsing module. (See the description of ocamlyacc below.) 10.2 Syntax of lexer definitions The format of lexer definitions is as follows: { header } rule entrypoint = 89 Chapter 10. Lexer and parser generators (ocamllex, ocamlyacc) 90 parse regexp { action } | ... | regexp { action } and entrypoint = parse ... and ... { trailer } Comments are delimited by (* and *), as in Caml. 10.2.1 Header and trailer The header and trailer sections are arbitrary Caml text enclosed in curly braces. Either or both can be omitted. If present, the header text is copied as is at the beginning of the output file and the trailer text at the end. Typically, the header section contains the open directives required by the actions, and possibly some auxiliary functions used in the actions. 10.2.2 Entry points The names of the entry points must be valid value identifiers. 10.2.3 Regular expressions The regular expressions are in the style of lex, with a more Caml-like syntax. ' char ' A character constant, with the same syntax as Objective Caml character constants. Match the denoted character. _ (Underscore.) Match any character. eof Match the end of the lexer input. " string " A string constant, with the same syntax as Objective Caml string constants. Match the corresponding sequence of characters. [ character-set ] Match any single character belonging to the given character set. Valid character sets are: single character constants ' c '; ranges of characters ' c1 ' - ' c2 ' (all characters between c1 and c2, inclusive); and the union of two or more character sets, denoted by concatenation. [ ^ character-set ] Match any single character not belonging to the given character set. regexp * (Repetition.) Match the concatenation of zero or more strings that match regexp. regexp + (Strict repetition.) Match the concatenation of one or more strings that match regexp. regexp ? (Option.) Match either the empty string, or a string matching regexp. Chapter 10. Lexer and parser generators (ocamllex, ocamlyacc) 91 regexp1 | regexp2 (Alternative.) Match any string that matches either regexp1 or regexp2 regexp1 regexp2 (Concatenation.) Match the concatenation of two strings, the first matching regexp1, the second matching regexp2. ( regexp ) Match the same strings as regexp. Concerning the precedences of operators, * and + have highest precedence, followed by ?, then concatenation, then | (alternation). 10.2.4 Actions The actions are arbitrary Caml expressions. They are evaluated in a context where the identifier lexbuf is bound to the current lexer buffer. Some typical uses for lexbuf, in conjunction with the operations on lexer buffers provided by the Lexing standard library module, are listed below. Lexing.lexeme lexbuf Return the matched string. Lexing.lexeme_char lexbuf n th Return the n character in the matched string. The first character corresponds to n=0. Lexing.lexeme_start lexbuf Return the absolute position in the input text of the beginning of the matched string. The first character read from the input text has position 0. Lexing.lexeme_end lexbuf Return the absolute position in the input text of the end of the matched string. The first character read from the input text has position 0. entrypoint lexbuf (Where entrypoint is the name of another entry point in the same lexer definition.) Recursively call the lexer on the given entry point. Useful for lexing nested comments, for example. 10.3 Overview of ocamlyacc The ocamlyacc command produces a parser from a context-free grammar specification with attached semantic actions, in the style of yacc. Assuming the input file is grammar.mly, executing ocamlyacc options grammar.mly produces Caml code for a parser in the file grammar.ml, and its interface in file grammar.mli. The generated module defines one parsing function per entry point in the grammar. These functions have the same names as the entry points. Parsing functions take as arguments a lexical analyzer (a function from lexer buffers to tokens) and a lexer buffer, and return the semantic attribute of the corresponding entry point. Lexical analyzer functions are usually generated Chapter 10. Lexer and parser generators (ocamllex, ocamlyacc) 92 from a lexer specification by the ocamllex program. Lexer buffers are an abstract data type implemented in the standard library module Lexing. Tokens are values from the concrete type token, defined in the interface file grammar.mli produced by ocamlyacc. 10.4 Syntax of grammar definitions Grammar definitions have the following format: %{ header %} declarations %% rules %% trailer Comments are enclosed between /* and */ (as in C) in the ``declarations'' and ``rules'' sections, and between (* and *) (as in Caml) in the ``header'' and ``trailer'' sections. 10.4.1 Header and trailer The header and the trailer sections are Caml code that is copied as is into file grammar.ml. Both sections are optional. The header goes at the beginning of the output file; it usually contains open directives and auxiliary functions required by the semantic actions of the rules. The trailer goes at the end of the output file. 10.4.2 Declarations Declarations are given one per line. They all start with a % sign. %token symbol...symbol Declare the given symbols as tokens (terminal symbols). These symbols are added as constant constructors for the token concrete type. %token < type > symbol...symbol Declare the given symbols as tokens with an attached attribute of the given type. These symbols are added as constructors with arguments of the given type for the token concrete type. The type part is an arbitrary Caml type expression, except that all type constructor names must be fully qualified (e.g. Modname.typename) for all types except standard built-in types, even if the proper open directives (e.g. open Modname) were given in the header section. That's because the header is copied only to the .ml output file, but not to the .mli output file, while the type part of a %token declaration is copied to both. %start symbol...symbol Declare the given symbols as entry points for the grammar. For each entry point, a parsing function with the same name is defined in the output module. Non-terminals that are not declared as entry points have no such parsing function. Start symbols must be given a type with the %type directive below. Chapter 10. Lexer and parser generators (ocamllex, ocamlyacc) 93 %type < type > symbol...symbol Specify the type of the semantic attributes for the given symbols. This is mandatory for start symbols only. Other nonterminal symbols need not be given types by hand: these types will be inferred when running the output files through the Objective Caml compiler (unless the -s option is in effect). The type part is an arbitrary Caml type expression, except that all type constructor names must be fully qualified, as explained above for %token. %left symbol...symbol %right symbol...symbol %nonassoc symbol...symbol Associate precedences and associativities to the given symbols. All symbols on the same line are given the same precedence. They have higher precedence than symbols declared before in a %left, %right or %nonassoc line. They have lower precedence than symbols declared after in a %left, %right or %nonassoc line. The symbols are declared to associate to the left (%left), to the right (%right), or to be non-associative (%nonassoc). The symbols are usually tokens. They can also be dummy nonterminals, for use with the %prec directive inside the rules. 10.4.3 Rules The syntax for rules is as usual: nonterminal : symbol ... symbol { semantic-action } | ... | symbol ... symbol { semantic-action } ; Rules can also contain the %prec symbol directive in the right-hand side part, to override the default precedence and associativity of the rule with the precedence and associativity of the given symbol. Semantic actions are arbitrary Caml expressions, that are evaluated to produce the semantic attribute attached to the defined nonterminal. The semantic actions can access the semantic attributes of the symbols in the right-hand side of the rule with the $ notation: $1 is the attribute for the first (leftmost) symbol, $2 is the attribute for the second symbol, etc. The rules may contain the special symbol error to indicate resynchronization points, as in yacc. Actions occurring in the middle of rules are not supported. 10.4.4 Error handling Error recovery is supported as follows: when the parser enters an error state, it calls a function named parse_error with the string syntax error as argument. The default parse_error function simply raises the Parsing.Parse_error exception, thus initiating error recovery (see below). The user can define a customized parse_error function in the header section of the grammar file. Chapter 10. Lexer and parser generators (ocamllex, ocamlyacc) 94 When the Parsing.Parse_error exception is raised, either explicitely in one of the actions or implicitly by the parse_error function, the parser enters error recovery mode: it discards states from the stack until it reaches a place where the error token can be shifted. It then discards tokens from the input until it finds three successive tokens that can be accepted, and starts processing with the first of these. If no state can be uncovered where the error token can be shifted, then the parser aborts by raising the Parsing.Parse_error exception. Refer to documentation on yacc for more details and guidance in how to use error recovery. 10.5 Options The ocamlyacc command recognizes the following options: -v Generate a description of the parsing tables and a report on conflicts resulting from ambiguities in the grammar. The description is put in file grammar.output. -bprefix Name the output files prefix.ml, prefix.mli, prefix.output, instead of the default naming convention. 10.6 A complete example The all-time favorite: a desk calculator. This program reads arithmetic expressions on standard input, one per line, and prints their values. Here is the grammar definition: /* File parser.mly */ %token INT %token PLUS MINUS TIMES DIV %token LPAREN RPAREN %token EOL %left PLUS MINUS /* lowest precedence */ %left TIMES DIV /* medium precedence */ %nonassoc UMINUS /* highest precedence */ %start main /* the entry point */ %type main %% main: expr EOL { $1 } ; expr: INT { $1 } | LPAREN expr RPAREN { $2 } | expr PLUS expr { $1 + $3 } | expr MINUS expr { $1 - $3 } | expr TIMES expr { $1 * $3 } | expr DIV expr { $1 / $3 } | MINUS expr %prec UMINUS { - $2 } ; Here is the definition for the corresponding lexer: (* File lexer.mll *) { Chapter 10. Lexer and parser generators (ocamllex, ocamlyacc) 95 open Parser (* The type token is defined in parser.mli *) exception Eof } rule token = parse [' ' '\t'] { token lexbuf } (* skip blanks *) | ['\n' ] { EOL } | ['0'-'9']+ { INT(int_of_string(Lexing.lexeme lexbuf)) } | '+' { PLUS } | '-' { MINUS } | '*' { TIMES } | '/' { DIV } | '(' { LPAREN } | ')' { RPAREN } | eof { raise Eof } Here is the main program, that combines the parser with the lexer: (* File calc.ml *) let _ = try let lexbuf = Lexing.from_channel stdin in while true do let result = Parser.main Lexer.token lexbuf in print_int result; print_newline(); flush stdout done with Lexer.Eof -> exit 0 To compile everything, execute: ocamllex lexer.mll # generates lexer.ml ocamlyacc parser.mly # generates parser.ml and parser.mli ocamlc -c parser.mli ocamlc -c lexer.ml ocamlc -c parser.ml ocamlc -c calc.ml ocamlc -o calc lexer.cmo parser.cmo calc.cmo Chapter 11 Dependency generator (ocamldep) The ocamldep command scans a set of Objective Caml source files (.ml and .mli files) for references to external compilation units, and outputs dependency lines in a format suitable for the make utility. This ensures that make will compile the source files in the correct order, and recompile those files that need to when a source file is modified. The typical usage is: ocamldep options *.mli *.ml > .depend where *.mli *.ml expands to all source files in the current directory and .depend is the file that should contain the dependencies. (See below for a typical Makefile.) Dependencies are generated both for compiling with the bytecode compiler ocamlc and with the native-code compiler ocamlopt. 11.1 Options The following command-line option is recognized by ocamldep. -I directory Add the given directory to the list of directories searched for source files. If a source file foo.ml mentions an external compilation unit Bar, a dependency on that unit's interface bar.cmi is generated only if the source for bar is found in the current directory or in one of the directories specified with -I. Otherwise, Bar is assumed to be a module form the standard library, and no dependencies are generated. For programs that span multiple directories, it is recommended to pass ocamldep the same -I options that are passed to the compiler. 11.2 A typical Makefile Here is a template Makefile for a Objective Caml program. CSLC=ocamlc CSLOPT=ocamlopt CSLDEP=ocamldep INCLUDES= #all relevant -I options here CSLFLAGS=$(INCLUDES) #add other options for ocamlc here CSLOPTFLAGS=$(INCLUDES) #add other options for ocamlopt here # prog1 should be compiled to bytecode, and is composed of three # units: mod1, mod2 and mod3. 96 Chapter 11. Dependency generator (ocamldep) 97 # The list of object files for prog1 PROG1_OBJS=mod1.cmo mod2.cmo mod3.cmo prog1: $(PROG1_OBJS) $(CSLC) -o prog1 $(CSLFLAGS) $(PROG1_OBJS) # prog2 should be compiled to native-code, and is composed of two # units: mod4 and mod5. # The list of object files for prog2 PROG2_OBJS=mod4.cmx mod5.cmx prog2: $(PROG2_OBJS) $(CSLOPT) -o prog2 $(CSLFLAGS) $(PROG2_OBJS) # Common rules .SUFFIXES: .ml .mli .cmo .cmi .cmx .ml.cmo: $(CSLC) $(CSLFLAGS) -c $< .mli.cmi: $(CSLC) $(CSLFLAGS) -c $< .ml.cmx: $(CSLOPT) $(CSLOPTFLAGS) -c $< # Clean up clean: rm -f prog1 prog2 rm -f *.cm[iox] # Dependencies depend: $(CSLDEP) $(INCLUDES) *.mli *.ml > .depend include .depend Chapter 12 Profiling (ocamlprof) This chapter describes how the execution of Objective Caml programs can be profiled, by recording how many times functions are called, branches of conditionals are taken, ... 12.1 Compiling for profiling Before profiling an execution, the program must be compiled in profiling mode, using the ocamlcp front-end to the ocamlc compiler (see chapter 6). When compiling modules separately, ocamlcp must be used when compiling the modules (production of .cmo files), and can also be used (though this is not strictly necessary) when linking them together. The amount of profiling information can be controlled through the -p option to ocamlcp, followed by one or several letters indicating which parts of the program should be profiled: a all options f function calls : a count point is set at the beginning of function bodies i if ...then ...else ... : count points are set in both then branch and else branch l while, for loops: a count point is set at the beginning of the loop body m match branches: a count point is set at the beginning of the body of each branch t try ...with ... branches: a count point is set at the beginning of the body of each branch For instance, compiling with ocamlcp -pfilm profiles function calls, if...then...else..., loops and pattern matching. Calling ocamlcp without the -p option defaults to -p fm, meaning that only function calls and pattern matching are profiled. 12.2 Profiling an execution Running a bytecode executable file that has been compiled with ocamlcp records the execution counts for the specified parts of the program and saves them in a file called ocamlprof.dump in the current directory. The ocamlprof.dump file is written only if the program terminates normally 98 Chapter 12. Profiling (ocamlprof) 99 (by calling exit or by falling through). It is not written if the program terminates with an uncaught exception. If a compatible dump file already exists in the current directory, then the profiling information is accumulated in this dump file. This allows, for instance, the profiling of several executions of a program on different inputs. 12.3 Printing profiling information The ocamlprof command produces a source listing of the program modules where execution counts have been inserted as comments. For instance, ocamlprof foo.ml prints the source code for the foo module, with comments indicating how many times the functions in this module have been called. Naturally, this information is accurate only if the source file has not been modified since the profiling execution took place. The following options are recognized by ocamlprof: -f dumpfile Specifies an alternate dump file of profiling information -F string Specifies an additional string to be output with profiling information. By default, ocamlprof will annotate programs with comments of the form (* n *) where n is the counter value for a profiling point. With option -F s, the annotation will be (* s n *). 12.4 Time profiling Profiling with ocamlprof only records execution counts, not the actual time spent into each function. There is currently no way to perform time profiling on bytecode programs generated by ocamlc. On native-code programs generated by ocamlopt, the standard Unix profiler prof can be used; just add the -ccopt -p option when linking the program: ocamlopt -o myprog -ccopt -p other-options files ./myprog prof myprog Function names in the output of prof have the following format: Module-name_function-name_unique-number Chapter 13 Interfacing C with Objective Caml This chapter describes how user-defined primitives, written in C, can be linked with Caml code and called from Caml functions. 13.1 Overview and compilation information 13.1.1 Declaring primitives User primitives are declared in an implementation file or struct...end module expression using the external keyword: external name : type = C-function-name This defines the value name name as a function with type type that executes by calling the given C function. For instance, here is how the input primitive is declared in the standard library module Pervasives: external input : in_channel -> string -> int -> int -> int = "input" Primitives with several arguments are always curried. The C function does not necessarily have the same name as the ML function. External functions thus defined can be specified in interface files or sig...end signatures either as regular values val name : type thus hiding their implementation as a C function, or explicitly as ``manifest'' external functions external name : type = C-function-name The latter is slightly more efficient, as it allows clients of the module to call directly the C function instead of going through the corresponding Caml function. 13.1.2 Implementing primitives User primitives with arity n<5 are implemented by C functions that take n arguments of type value, and return a result of type value. The type value is the type of the representations for Caml Light values. It encodes objects of several base types (integers, floating-point numbers, strings, ...), as well as Caml Light data structures. The type value and the associated conversion 100 Chapter 13. Interfacing C with Objective Caml 101 functions and macros are described in details below. For instance, here is the declaration for the C function implementing the input primitive: value input(channel, buffer, offset, length) value channel, buffer, offset, length; { ... } When the primitive function is applied in a Caml Light program, the C function is called with the values of the expressions to which the primitive is applied as arguments. The value returned by the function is passed back to the Caml Light program as the result of the function application. User primitives with arity greater than 5 should be implemented by two C functions. The first function, to be used in conjunction with the bytecode compiler ocamlc, receives two arguments: a pointer to an array of Caml Light values (the values for the arguments), and an integer which is the number of arguments provided. The other function, to be used in conjunction with the native-code compiler ocamlopt, takes its arguments directly. For instance, here are the two C functions for the 7-argument primitive Nat.add_nat: value add_nat_native(nat1, ofs1, len1, nat2, ofs2, len2, carry_in) value nat1, ofs1, len1, nat2, ofs2, len2, carry_in; { ... } value add_nat_bytecode(argv, argn) value * argv; int argn; { return add_nat_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]); } The names of the two C functions must be given in the primitive declaration, as follows: external name : type = bytecode-C-function-name native-code-C-function-name For instance, in the case of add_nat, the declaration is: external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "add_nat_bytecode" "add_nat_native" Implementing a user primitive is actually two separate tasks: on the one hand, decoding the arguments to extract C values from the given Caml Light values, and encoding the return value as a Caml Light value; on the other hand, actually computing the result from the arguments. Except for very simple primitives, it is often preferable to have two distinct C functions to implement these two tasks. The first function actually implements the primitive, taking native C values as arguments and returning a native C value. The second function, often called the ``stub code'', is a simple wrapper around the first function that converts its arguments from Caml Light values to C values, call the first function, and convert the returned C value to Caml Light value. For instance, here is the stub code for the input primitive: value input(channel, buffer, offset, length) Chapter 13. Interfacing C with Objective Caml 102 value channel, buffer, offset, length; { return Val_long(getblock((struct channel *) channel, &Byte(buffer, Long_val(offset)), Long_val(length))); } (Here, Val_long, Long_val and so on are conversion macros for the type value, that will be described later.) The hard work is performed by the function getblock, which is declared as: long getblock(channel, p, n) struct channel * channel; char * p; long n; { ... } To write C code that operates on Objective Caml values, the following include files are provided: --------------------------------------------------------------------------- |Include file |Provides | --------------------------------------------------------------------------- |caml/mlvalues.h |definition of the value type, and conversion macros | |caml/alloc.h |allocation functions (to create structured Caml Light | | |objects) | |caml/memory.h |miscellaneous memory-related functions (for in-place | | |modification of structures, etc). | --------------------------------------------------------------------------- These files reside in the caml/ subdirectory of the Caml Light standard library directory (usually /usr/local/lib/caml-light). 13.1.3 Linking C code with Caml code The Objective Caml runtime system comprises three main parts: the bytecode interpreter, the memory manager, and a set of C functions that implement the primitive operations. Some bytecode instructions are provided to call these C functions, designated by their offset in a table of functions (the table of primitives). In the default mode, the Caml linker produces bytecode for the standard runtime system, with a standard set of primitives. References to primitives that are not in this standard set result in the ``unavailable C primitive'' error. In the ``custom runtime'' mode, the Caml linker scans the object files and determines the set of required primitives. Then, it builds a suitable runtime system, by calling the native code linker with: - the table of the required primitives - a library that provides the bytecode interpreter, the memory manager, and the standard primitives - libraries and object code files (.o files) mentioned on the command line for the Caml Light linker, that provide implementations for the user's primitives. This builds a runtime system with the required primitives. The Caml linker Chapter 13. Interfacing C with Objective Caml 103 generates bytecode for this custom runtime system. The bytecode is appended to the end of the custom runtime system, so that it will be automatically executed when the output file (custom runtime + bytecode) is launched. To link in ``custom runtime'' mode, execute the ocamlc command with: - the -custom option - the names of the desired Caml object files (.cmo files) - the names of the C object files and libraries (.o and .a files) that implement the required primitives. (Under Unix, a library named libname.a residing in one of the standard library directories can also be specified as -cclib -lname.) 13.2 The value type All Caml objects are represented by the C type value, defined in the include file caml/mlvalues.h, along with macros to manipulate values of that type. An object of type value is either: - an unboxed integer - a pointer to a block inside the heap (such as the blocks allocated through one of the alloc_* functions below) - a pointer to an object outside the heap (e.g., a pointer to a block allocated by malloc, or to a C variable). 13.2.1 Integer values Integer values encode 31-bit signed integers (63-bit on 64-bit architectures). They are unboxed (unallocated). 13.2.2 Blocks Blocks in the heap are garbage-collected, and therefore have strict structure constraints. Each block includes a header containing the size of the block (in words), and the tag of the block. The tag governs how the contents of the blocks are structured. A tag lower than No_scan_tag indicates a structured block, containing well-formed values, which is recursively traversed by the garbage collector. A tag greater than or equal to No_scan_tag indicates a raw block, whose contents are not scanned by the garbage collector. For the benefits of ad-hoc polymorphic primitives such as equality and structured input-output, structured and raw blocks are further classified according to their tags as follows: Chapter 13. Interfacing C with Objective Caml 104 --------------------------------------------------------------------- |Tag |Contents of the block | --------------------------------------------------------------------- |0 to No_scan_tag- 1 |A structured block (an array of Caml objects). | | |Each field is a value. | |Closure_tag |A closure representing a functional value. | | |The first word is a pointer to a piece | | |of bytecode, the remaining words are value | | |containing the environment. | |String_tag |A character string. | |Double_tag |A double-precision floating-point number. | |Double_array_tag |An array of double-precision floating-point | | |numbers (for the native-code compiler only). | |Abstract_tag |A block representing an abstract datatype. | |Final_tag |A block representing an abstract datatype with | | |a ``finalization'' function, to be called when | | |the block is deallocated. | --------------------------------------------------------------------- 13.2.3 Pointers to outside the heap Any word-aligned pointer to outside the heap can be safely cast to and from the type value. This includes pointers returned by malloc, and pointers to C variables (of size at least one word) obtained with the & operator. 13.3 Representation of Caml Light data types This section describes how Caml Light data types are encoded in the value type. 13.3.1 Atomic types ------------------------------------------------- |Caml type |Encoding | ------------------------------------------------- |int |Unboxed integer values. | |char |Unboxed integer values (ASCII code). | |float |Blocks with tag Double_tag. | |string |Blocks with tag String_tag. | ------------------------------------------------- 13.3.2 Tuples and records Tuples are represented by pointers to blocks, with tag 0. Records are also represented by zero-tagged blocks. The ordering of labels in the record type declaration determines the layout of the record fields: the value associated to the label declared first is stored in field 0 of the block, the value associated to the label declared next goes in field 1, and so on. The native-code compiler represents specially records whose fields all have type float. These are represented as arrays of floating-point numbers, with tag Double_array_tag. (See the section below on arrays.) 13.3.3 Arrays In the bytecode compiler, all arrays are represented like tuples, that is, as pointers to blocks tagged 0. The native-code compiler has a special, unboxed, more efficient representation for arrays of floating-point numbers (type float array). These arrays are represented by pointers to blocks with tag Double_array_tag. They should be accessed with the Double_field and Store_double_field macros. Arrays of floating-point numbers in the bytecode compiler should be accessed with Double_val(Field(v, n)) for reading and modify(&Field(v, n), Chapter 13. Interfacing C with Objective Caml 105 copy_double(d)) for writing. 13.3.4 Concrete types Constructed terms are represented either by unboxed integers (for constant constructors) or by blocks whose tag encode the constructor (for non-constant constructors). The constant constructors and the non-constant constructors for a given concrete type are numbered separately, starting from 0, in the order in which they appear in the concrete type declaration. Constant constructors are represented by unboxed integers equal to the constructor number. Non-constant constructors declared with a n-tuple as argument are represented by a block of size n, tagged with the constructor number; the n fields contain the components of its tuple argument. Other non-constant constructors are represented by a block of size 1, tagged with the constructor number; the field 0 contains the value of the constructor argument. Example: --------------------------------------------------------- |Constructed term |Representation | --------------------------------------------------------- |() |Val_int(0) | |false |Val_int(0) | |true |Val_int(1) | |[] |Val_int(0) | |h::t |Block with size = 2 and tag = 0; | | |first field contains h, second field | | |t | --------------------------------------------------------- As a convenience, caml/mlvalues.h defines the macros Val_unit, Val_false and Val_true to refer to (), false and true. 13.3.5 Objects Objects are represented as zero-tagged blocks. The first field of the block refers to the object class and associated method suite, in a format that cannot easily be exploited from C. The remaining fields of the object contain the values of the instance variables of the object. Instance variables are stored in the order in which they appear in the class definition (taking inherited classes into account). 13.4 Operations on values 13.4.1 Kind tests - Is_long(v) is true if value v is an immediate integer, false otherwise - Is_block(v) is true if value v is a pointer to a block, and false if it is an immediate integer. 13.4.2 Operations on integers - Val_long(l) returns the value encoding the long int l - Long_val(v) returns the long int encoded in value v - Val_int(i) returns the value encoding the int i - Int_val(v) returns the int encoded in value v Chapter 13. Interfacing C with Objective Caml 106 13.4.3 Accessing blocks - Wosize_val(v) returns the size of value v, in words, excluding the header. - Tag_val(v) returns the tag of value v. th - Field(v, n) returns the value contained in the n field of the structured block v. Fields are numbered from 0 to Wosize_val(v)-1. - Code_val(v) returns the code part of the closure v. - string_length(v) returns the length (number of characters) of the string v. th - Byte(v, n) returns the n character of the string v, with type char. Characters are numbered from 0 to string_length(v)-1. th - Byte_u(v, n) returns the n character of the string v, with type unsigned char. Characters are numbered from 0 to string_length(v)-1. - String_val(v) returns a pointer to the first byte of the string v, with type char *. This pointer is a valid C string: there is a null character after the last character in the string. However, Caml Light strings can contain embedded null characters, that will confuse the usual C functions over strings. - Double_val(v) returns the floating-point number contained in value v, with type double. th - (Native-code only.) Double_field(v, n) returns the n element of the array of floating-point numbers v (a block tagged Double_array_tag). - (Native-code only.) Store_double_field(v, n, d) stores the double th precision floating-point number d in the n element of the array of floating-point numbers v. The expressions Field(v, n), Byte(v, n), Byte_u(v, n), and Double_val(v) are valid l-values. Hence, they can be assigned to, resulting in an in-place modification of value v. Assigning directly to Field(v, n) must be done with care to avoid confusing the garbage collector (see below). 13.4.4 Allocating blocks From the standpoint of the allocation functions, blocks are divided according to their size as zero-sized blocks, small blocks (with size less than or equal to Max_young_wosize), and large blocks (with size greater than to Max_young_wosize). The constant Max_young_wosize is declared in the include file mlvalues.h. It is guaranteed to be at least 64 (words), so that any block with constant size less than or equal to 64 can be assumed to be small. For blocks whose size is computed at run-time, the size must be compared against Max_young_wosize to determine the correct allocation procedure. Chapter 13. Interfacing C with Objective Caml 107 - Atom(t) returns an ``atom'' (zero-sized block) with tag t. Zero-sized blocks are preallocated outside of the heap. It is incorrect to try and allocate a zero-sized block using the functions below. For instance, Atom(0) represents the empty array. - alloc(n, t) returns a fresh small block of size n window = "curses_initscr" external endwin: unit -> unit = "curses_endwin" external refresh: unit -> unit = "curses_refresh" external wrefresh : window -> unit = "curses_wrefresh" external newwin: int -> int -> int -> int -> window = "curses_newwin" external mvwin: window -> int -> int -> unit = "curses_mvwin" external addch: char -> unit = "curses_addch" external mvwaddch: window -> int -> int -> char -> unit = "curses_mvwaddch" external addstr: string -> unit = "curses_addstr" external mvwaddstr: window -> int -> int -> string - > unit = "curses_mvwaddstr" (* lots more omitted *) To compile this interface: ocamlc -c curses.mli To implement these functions, we just have to provide the stub code; the core functions are already implemented in the curses library. The stub code file, curses.o, looks like: #include #include value curses_initscr(unit) value unit; { return (value) initscr(); /* OK to coerce directly from WIN- DOW * to value since that's a block created by malloc() */ } value curses_wrefresh(win) Chapter 13. Interfacing C with Objective Caml 111 value win; { wrefresh((WINDOW *) win); return Val_unit; } value curses_newwin(nlines, ncols, x0, y0) value nlines, ncols, x0, y0; { return (value) newwin(Int_val(nlines), Int_val(ncols), Int_val(x0), Int_val(y0)); } value curses_addch(c) value c; { addch(Int_val(c)); /* Characters are encoded like integers */ return Val_unit; } value curses_addstr(s) value s; { addstr(String_val(s)); return Val_unit; } /* This goes on for pages. */ (Actually, it would be better to create a library for the stub code, with each stub code function in a separate file, so that linking would pick only those functions from the curses library that are actually used.) The file curses.c can be compiled with: cc -c -I/usr/local/lib/ocaml curses.c or, even simpler, ocamlc -c curses.c (When passed a .c file, the ocamlc command simply calls the C compiler on that file, with the right -I option.) Now, here is a sample Caml program test.ml that uses the curses module: open Curses let main_window = initscr () in let small_window = newwin 10 5 20 10 in mvwaddstr main_window 10 2 "Hello"; mvwaddstr small_window 4 3 "world"; refresh(); for i = 1 to 100000 do () done; endwin() To compile this program, run: ocamlc -c test.ml Finally, to link everything together: Chapter 13. Interfacing C with Objective Caml 112 ocamlc -custom -o test test.cmo curses.o -cclib -lcurses Part IV The Objective Caml library 113 Chapter 14 The core library This chapter describes the functions provided by the Caml Light core library module: module Pervasives. This module is special in two ways: - It is automatically linked with the user's object code files by the ocamlc command (chapter 6). - It is automatically ``opened'' when a compilation starts, or when the toplevel system is launched. Hence, it is possible to use unqualified identifiers to refer to the functions provided by the Pervasives module, without adding a open Pervasives directive. Conventions The declarations from the signature of the Pervasives module are printed one by one in typewriter font, followed by a short comment. All modules and the identifiers they export are indexed at the end of this report. 14.1 Module Pervasives: the initially opened module This module provides the built-in types (numbers, booleans, strings, exceptions, references, lists, arrays, input-output channels, ...) and the basic operations over these types. This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by Pervasives. Predefined types type int The type of integer numbers. type char The type of characters. type string The type of character strings. 114 Chapter 14. The core library 115 type float The type of floating-point numbers. type bool The type of booleans (truth values). type unit = () The type of the unit value. type exn The type of exception values. type 'a array The type of arrays whose elements have type 'a. type 'a list = [] | :: of 'a * 'a list The type of lists whose elements have type 'a. type 'a option = None | Some of 'a The type of optional values. type ('a, 'b, 'c) format The type of format strings. 'a is the type of the parameters of the format, 'c is the result type for the printf-style function, and 'b is the type of the first argument given to %a and %t printing functions (see module Printf). Exceptions val raise : exn -> 'a Raise the given exception value exception Match_failure of string * int * int Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the pattern-matching in the source code (file name, position of first character, position of last character). exception Invalid_argument of string Exception raised by library functions to signal that the given arguments do not make sense. exception Failure of string Exception raised by library functions to signal that they are undefined on the given arguments. Chapter 14. The core library 116 exception Not_found Exception raised by search functions when the desired object could not be found. exception Out_of_memory Exception raised by the garbage collector when there is insufficient memory to complete the computation. exception Sys_error of string Exception raised by the input/output functions to report an operating system error. exception End_of_file Exception raised by input functions to signal that the end of file has been reached. exception Division_by_zero Exception raised by division and remainder operations when their second argument is null. exception Exit This exception is not raised by any library function. It is provided for use in your programs. val invalid_arg: string -> 'a Raise exception Invalid_argument with the given string. val failwith: string -> 'a Raise exception Failure with the given string. Comparisons val (=) : 'a -> 'a -> bool e1 = e2 tests for structural equality of e1 and e2. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises Invalid_argument. Equality between cyclic data structures may not terminate. val (<>) : 'a -> 'a -> bool Negation of (=). val (<) : 'a -> 'a -> bool val (>) : 'a -> 'a -> bool val (<=) : 'a -> 'a -> bool val (>=) : 'a -> 'a -> bool Chapter 14. The core library 117 Structural ordering functions. These functions coincide with the usual orderings over integer, string and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with (=). As in the case of (=), mutable structures are compared by contents. Comparison between functional values raises Invalid_argument. Comparison between cyclic structures may not terminate. val compare: 'a -> 'a -> int = "compare" "noalloc" compare x y returns 0 if x=y, a negative integer if xy. The same restrictions as for = apply. compare can be used as the comparison function required by the Set and Map modules. val min: 'a -> 'a -> 'a Return the smaller of the two arguments. val max: 'a -> 'a -> 'a Return the greater of the two arguments. val (==) : 'a -> 'a -> bool e1 == e2 tests for physical equality of e1 and e2. On integers and characters, it is the same as structural equality. On mutable structures, e1 == e2 is true if and only if physical modification of e1 also affects e2. On non-mutable structures, the behavior of (==) is implementation-dependent, except that e1 == e2 implies e1 = e2. val (!=) : 'a -> 'a -> bool Negation of (==). Boolean operations val not : bool -> bool The boolean negation. val (&) : bool -> bool -> bool val (&&) : bool -> bool -> bool The boolean ``and''. Evaluation is sequential, left-to-right: in e1 & e2, e1 is evaluated first, and if it returns false, e2 is not evaluated at all. val (or) : bool -> bool -> bool val (||) : bool -> bool -> bool The boolean ``or''. Evaluation is sequential, left-to-right: in e1 or e2, e1 is evaluated first, and if it returns true, e2 is not evaluated at all. Chapter 14. The core library 118 Integer arithmetic Integers are 31 bits wide (or 63 bits on 64-bit processors). All 31 63 operations are taken modulo 2 (or 2 ). They do not fail on overflow. val (~-) : int -> int Unary negation. You can also write -e instead of ~-e. val succ : int -> int succ x is x+1. val pred : int -> int pred x is x-1. val (+) : int -> int -> int Integer addition. val (-) : int -> int -> int Integer subtraction. val (*) : int -> int -> int Integer multiplication. val (/) : int -> int -> int val (mod) : int -> int -> int Integer division and remainder. Raise Division_by_zero if the second argument is 0. If one of the arguments is negative, the result is platform-dependent. val abs : int -> int Return the absolute value of the argument. val max_int: int val min_int: int The greatest and smallest representable integers. Bitwise operations val (land) : int -> int -> int Bitwise logical and. val (lor) : int -> int -> int Bitwise logical or. Chapter 14. The core library 119 val (lxor) : int -> int -> int Bitwise logical exclusive or. val lnot: int -> int Bitwise logical negation. val (lsl) : int -> int -> int n lsl m shifts n to the left by m bits. val (lsr) : int -> int -> int n lsr m shifts n to the right by m bits. This is a logical shift: zeroes are inserted regardless of the sign of n. val (asr) : int -> int -> int n asr m shifts n to the right by m bits. This is an arithmetic shift: the sign bit of n is replicated. Floating-point arithmetic On most platforms, Caml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations do not fail on overflow or underflow, but return denormal numbers. val (~-.) : float -> float Unary negation. You can also write -.e instead of ~-.e. val (+.) : float -> float -> float Floating-point addition val (-.) : float -> float -> float Floating-point subtraction val (*.) : float -> float -> float Floating-point multiplication val (/.) : float -> float -> float Floating-point division. val (**) : float -> float -> float = "power_float" "pow" "float" Exponentiation val exp : float -> float = "exp_float" "exp" "float" val log : float -> float = "log_float" "log" "float" val sqrt : float -> float = "sqrt_float" "sqrt" "float" val sin : float -> float = "sin_float" "sin" "float" Chapter 14. The core library 120 val cos : float -> float = "cos_float" "cos" "float" val tan : float -> float = "tan_float" "tan" "float" val asin : float -> float = "asin_float" "asin" "float" val acos : float -> float = "acos_float" "acos" "float" val atan : float -> float = "atan_float" "atan" "float" val atan2 : float -> float -> float = "atan2_float" "atan2" "float" Usual transcendental functions on floating-point numbers. val abs_float : float -> float Return the absolute value of the argument. val float : int -> float Convert an integer to floating-point. val truncate : float -> int Truncate the given floating-point number to an integer. The result is unspecified if it falls outside the range of representable integers. String operations More string operations are provided in module String. val (^) : string -> string -> string String concatenation. String conversion functions val string_of_bool : bool -> string Return the string representation of a boolean. val string_of_int : int -> string Return the string representation of an integer, in decimal. val int_of_string : string -> int Convert the given string to an integer. The string is read in decimal (by default) or in hexadecimal, octal or binary if the string begins with 0x, 0o or 0b respectively. Raise Failure "int_of_string" if the given string is not a valid representation of an integer. val string_of_float : float -> string Return the string representation of a floating-point number. val float_of_string : string -> float Convert the given string to a float. The result is unspecified if the given string is not a valid representation of a float. Chapter 14. The core library 121 Pair operations val fst : 'a * 'b -> 'a Return the first component of a pair. val snd : 'a * 'b -> 'b Return the second component of a pair. List operations More list operations are provided in module List. val (@) : 'a list -> 'a list -> 'a list List concatenation. Input/output type in_channel type out_channel The types of input channels and output channels. val stdin : in_channel val stdout : out_channel val stderr : out_channel The standard input, standard output, and standard error output for the process. Output functions on standard output val print_char : char -> unit Print a character on standard output. val print_string : string -> unit Print a string on standard output. val print_int : int -> unit Print an integer, in decimal, on standard output. val print_float : float -> unit Print a floating-point number, in decimal, on standard output. val print_endline : string -> unit Print a string, followed by a newline character, on standard output. Chapter 14. The core library 122 val print_newline : unit -> unit Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. Output functions on standard error val prerr_char : char -> unit Print a character on standard error. val prerr_string : string -> unit Print a string on standard error. val prerr_int : int -> unit Print an integer, in decimal, on standard error. val prerr_float : float -> unit Print a floating-point number, in decimal, on standard error. val prerr_endline : string -> unit Print a string, followed by a newline character on standard error and flush standard error. val prerr_newline : unit -> unit Print a newline character on standard error, and flush standard error. Input functions on standard input val read_line : unit -> string Flush standard output, then read characters from standard input until a newline character is encountered. Return the string of all characters read, without the newline character at the end. val read_int : unit -> int Flush standard output, then read one line from standard input and convert it to an integer. Raise Failure "int_of_string" if the line read is not a valid representation of an integer. val read_float : unit -> float Flush standard output, then read one line from standard input and convert it to a floating-point number. The result is unspecified if the line read is not a valid representation of a floating-point number. Chapter 14. The core library 123 General output functions type open_flag = Open_rdonly | Open_wronly | Open_append | Open_creat | Open_trunc | Open_excl | Open_binary | Open_text | Open_nonblock Opening modes for open_out_gen and open_in_gen. Open_rdonly: open for reading. Open_wronly: open for writing. Open_append: open for appending. Open_creat: create the file if it does not exist. Open_trunc: empty the file if it already exists. Open_excl: fail if the file already exists. Open_binary: open in binary mode (no conversion). Open_text: open in text mode (may perform conversions). Open_nonblock: open in non-blocking mode. val open_out : string -> out_channel Open the named file for writing, and return a new output channel on that file, positionned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. Raise Sys_error if the file could not be opened. val open_out_bin : string -> out_channel Same as open_out, but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like open_out. val open_out_gen : open_flag list -> int -> string -> out_channel open_out_gen mode rights filename opens the file named filename for writing, as above. The extra argument mode specify the opening mode. The extra argument rights specifies the file permissions, in case the file must be created. open_out and open_out_bin are special cases of this function. val flush : out_channel -> unit Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. val output_char : out_channel -> char -> unit Write the character on the given output channel. val output_string : out_channel -> string -> unit Write the string on the given output channel. val output : out_channel -> string -> int -> int -> unit Chapter 14. The core library 124 output chan buff ofs len writes len characters from string buff, starting at offset ofs, to the output channel chan. Raise Invalid_argument "output" if ofs and len do not designate a valid substring of buff. val output_byte : out_channel -> int -> unit Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. val output_binary_int : out_channel -> int -> unit Write one integer in binary format on the given output channel. The only reliable way to read it back is through the input_binary_int function. The format is compatible across all machines for a given version of Caml Light. val output_value : out_channel -> 'a -> unit Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function input_value. The format is compatible across all machines for a given version of Caml Light. val seek_out : out_channel -> int -> unit seek_out chan pos sets the current writing position to pos for channel chan. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. val pos_out : out_channel -> int Return the current writing position for the given channel. val out_channel_length : out_channel -> int Return the total length (number of characters) of the given channel. This works only for regular files. On files of other kinds, the result is meaningless. val close_out : out_channel -> unit Close the given channel, flushing all buffered write operations. The behavior is unspecified if any of the functions above is called on a closed channel. General input functions val open_in : string -> in_channel Open the named file for reading, and return a new input channel on that file, positionned at the beginning of the file. Raise Sys_error if the file could not be opened. val open_in_bin : string -> in_channel Chapter 14. The core library 125 Same as open_in, but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like open_in. val open_in_gen : open_flag list -> int -> string -> in_channel open_in_gen mode rights filename opens the file named filename for reading, as above. The extra arguments mode and rights specify the opening mode and file permissions. open_in and open_in_bin are special cases of this function. val input_char : in_channel -> char Read one character from the given input channel. Raise End_of_file if there are no more characters to read. val input_line : in_channel -> string Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. Raise End_of_file if the end of the file is reached at the beginning of line. val input : in_channel -> string -> int -> int -> int input chan buff ofs len attempts to read len characters from channel chan, storing them in string buff, starting at character number ofs. It returns the actual number of characters read, between 0 and len (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and len exclusive means that no more characters were available at that time; input must be called again to read the remaining characters, if desired. Exception Invalid_argument "input" is raised if ofs and len do not designate a valid substring of buff. val really_input : in_channel -> string -> int -> int -> unit really_input chan buff ofs len reads len characters from channel chan, storing them in string buff, starting at character number ofs. Raise End_of_file if the end of file is reached before len characters have been read. Raise Invalid_argument "really_input" if ofs and len do not designate a valid substring of buff. val input_byte : in_channel -> int Same as input_char, but return the 8-bit integer representing the character. Raise End_of_file if an end of file was reached. val input_binary_int : in_channel -> int Read an integer encoded in binary format from the given input channel. See output_binary_int. Raise End_of_file if an end of file was reached while reading the integer. val input_value : in_channel -> 'a Read the representation of a structured value, as produced by output_value or output_compact_value, and return the corresponding value. Chapter 14. The core library 126 This is not type-safe. The type of the returned object is not 'a properly speaking: the returned object has one unique type, which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax: (input_value chan : type). The behavior is unspecified if the object in the file does not belong to the given type. val seek_in : in_channel -> int -> unit seek_in chan pos sets the current reading position to pos for channel chan. This works only for regular files. On files of other kinds, the behavior is unspecified. val pos_in : in_channel -> int Return the current reading position for the given channel. val in_channel_length : in_channel -> int Return the total length (number of characters) of the given channel. This works only for regular files. On files of other kinds, the result is meaningless. val close_in : in_channel -> unit Close the given channel. Anything can happen if any of the functions above is called on a closed channel. References type 'a ref = { mutable contents: 'a } The type of references (mutable indirection cells) containing a value of type 'a. val ref : 'a -> 'a ref Return a fresh reference containing the given value. val (!) : 'a ref -> 'a !r returns the current contents of reference r. Could be defined as fun r -> r.contents. val (:=) : 'a ref -> 'a -> unit r := a stores the value of a in reference r. Could be defined as fun r v -> r.contents <- v. val incr : int ref -> unit Increment the integer contained in the given reference. Could be defined as fun r -> r := succ !r. val decr : int ref -> unit Chapter 14. The core library 127 Decrement the integer contained in the given reference. Could be defined as fun r -> r := pred !r. Program termination val exit : int -> 'a Flush all pending writes on stdout and stderr, and terminate the process, returning the given status code to the operating system (usually 0 to indicate no errors, and a small positive integer to indicate failure.) An implicit exit 0 is performed each time a program terminates normally (but not if it terminates because of an uncaught exception). val at_exit: (unit -> unit) -> unit Register the given function to be called at program termination time. The functions registered with at_exit will be called in some unspecified order when the program executes exit. They will not be called if the program terminates because of an uncaught exception. Chapter 15 The standard library This chapter describes the functions provided by the Caml Light standard library. The modules from the standard library are automatically linked with the user's object code files by the ocamlc command. Hence, these modules can be used in standalone programs without having to add any .cmo file on the command line for the linking phase. Similarly, in interactive use, these globals can be used in toplevel phrases without having to load any .cmo file in memory. Unlike the Pervasive module from the core library, the modules from the standard library are not automatically ``opened'' when a compilation starts, or when the toplevel system is launched. Hence it is necessary to use qualified identifiers to refer to the functions provided by these modules, or to add open directives. Conventions For easy reference, the modules are listed below in alphabetical order of module names. For each module, the declarations from its signature are printed one by one in typewriter font, followed by a short comment. All modules and the identifiers they export are indexed at the end of this report. Overview Here is a short listing, by theme, of the standard library modules. Data structures: Char p. 131 character operations String p. 155 string operations Array p. 130 array operations List p. 144 list operations Sort p. 153 sorting and merging lists Hashtbl p. 141 hash tables and hash functions Random p. 150 pseudo-random number generator Set p. 151 sets over ordered types Map p. 146 association tables over ordered types Oo p. 148 useful functions on objects Stack p. 153 last-in first-out stacks Queue p. 150 first-in first-out queues 128 Chapter 15. The standard library 129 Input/output: Format p. 133 pretty printing Printf p. 149 formatting printing functions Digest p. 132 MD5 message digest Parsing: Genlex p. 140 a generic lexer over streams Lexing p. 143 the run-time library for lexers generated by camllex Parsing p. 148 the run-time library for parsers generated by camlyacc Stream p. 154 basic functions over streams System interface: Arg p. 129 parsing of command line arguments Filename p. 132 operations on file names Gc p. 139 memory management control and statistics Printexc p. 148 a catch-all exception handler Sys p. 156 system interface 15.1 Module Arg: parsing of command line arguments This module provides a general mechanism for extracting options and arguments from the command line to the program. Syntax of command lines: A keyword is a character string starting with a -. An option is a keyword alone or followed by an argument. There are six types of keywords: Unit, String, Int, and Float. Unit, Set_flag and Clear_flag keywords do not take an argument. String, Int, and Float keywords take the following word on the command line as an argument. Arguments not preceded by a keyword are called anonymous arguments. Examples (cmd is assumed to be the command name): cmd -flag (a unit option) cmd -int 1 (an int option with argument 1) cmd -string foobar (a string option with argument "foobar") cmd -float 12.34 (a float option with argument 12.34) cmd 1 2 3 (three anonymous arguments: "1", "2", and "3") type spec = Unit of (unit -> unit) (* Call the function with no argument *) | Set of bool ref (* Set the reference to true *) | Clear of bool ref (* Set the reference to false *) | String of (string -> unit) (* Call the function with a string argument *) | Int of (int -> unit) (* Call the function with an int argument *) | Float of (float -> unit) (* Call the function with a float argument *) The concrete type describing the behavior associated with a keyword. val parse : (string * spec) list -> (string -> unit) -> unit parse speclist anonfun parses the command line, calling the functions in speclist whenever appropriate, and anonfun on anonymous arguments. The functions are called in the same order as they appear on the command line. The strings in the (string * spec) list are keywords and must Chapter 15. The standard library 130 start with a -, else they are ignored. exception Bad of string Functions in speclist or anonfun can raise Bad with an error message to reject invalid arguments. 15.2 Module Array: array operations val length : 'a array -> int Return the length (number of elements) of the given array. val get: 'a array -> int -> 'a Array.get a n returns the element number n of array a. The first element has number 0. The last element has number Array.length a - 1. Raise Invalid_argument "Array.get" if n is outside the range 0 to (Array.length a - 1). You can also write a.(n) instead of Array.get a n. val set: 'a array -> int -> 'a -> unit Array.set a n x modifies array a in place, replacing element number n with x. Raise Invalid_argument "Array.set" if n is outside the range 0 to Array.length a - 1. You can also write a.(n) <- x instead of Array.set a n x. val create: int -> 'a -> 'a array Array.create n x returns a fresh array of length n, initialized with x. All the elements of this new array are initially physically equal to x (in the sense of the == predicate). Consequently, if x is mutable, it is shared among all elements of the array, and modifying x through one of the array entries will modify all other entries at the same time. val create_matrix: int -> int -> 'a -> 'a array array Array.create_matrix dimx dimy e returns a two-dimensional array (an array of arrays) with first dimension dimx and second dimension dimy. All the elements of this new matrix are initially physically equal to e. The element (x,y) of a matrix m is accessed with the notation m.(x).(y). val append: 'a array -> 'a array -> 'a array Array.append v1 v2 returns a fresh array containing the concatenation of arrays v1 and v2. val concat: 'a array list -> 'a array Same as Array.append, but catenates a list of arrays. val sub: 'a array -> int -> int -> 'a array Array.sub a start len returns a fresh array of length len, containing the elements number start to start + len - 1 of array a. Raise Invalid_argument "Array.sub" if start and len do not designate a valid Chapter 15. The standard library 131 subarray of a; that is, if start < 0, or len < 0, or start + len > Array.length a. val copy: 'a array -> 'a array Array.copy a returns a copy of a, that is, a fresh array containing the same elements as a. val fill: 'a array -> int -> int -> 'a -> unit Array.fill a ofs len x modifies the array a in place, storing x in elements number ofs to ofs + len - 1. Raise Invalid_argument "Array.fill" if ofs and len do not designate a valid subarray of a. val blit: 'a array -> int -> 'a array -> int -> int -> unit Array.blit v1 o1 v2 o2 len copies len elements from array v1, starting at element number o1, to array v2, starting at element number o2. It works correctly even if v1 and v2 are the same array, and the source and destination chunks overlap. Raise Invalid_argument "Array.blit" if o1 and len do not designate a valid subarray of v1, or if o2 and len do not designate a valid subarray of v2. val iter: ('a -> 'b) -> 'a array -> unit Array.iter f a applies function f in turn to all the elements of a, discarding all the results: f a.(0); f a.(1); ...; f a.(Array.length a - 1); (). val map: ('a -> 'b) -> 'a array -> 'b array Array.map f a applies function f to all the elements of a, and builds an array with the results returned by f: [| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]. val to_list: 'a array -> 'a list Array.to_list a returns the list of all the elements of a. val of_list: 'a list -> 'a array Array.of_list l returns a fresh array containing the elements of l. 15.3 Module Char: character operations val code: char -> int Return the ASCII code of the argument. val chr: int -> char Return the character with the given ASCII code. Raise Invalid_argument "Char.chr" if the argument is outside the range 0--255. Chapter 15. The standard library 132 val escaped : char -> string Return a string representing the given character, with special characters escaped following the lexical conventions of Caml Light. 15.4 Module Digest: MD5 message digest This module provides functions to compute 128-bit ``digests'' of arbitrary-length strings or files. The digests are cryptographic quality: it is very hard, given a digest, to forge a string having that digest. The algorithm used is MD5. type t = string The type of digests: 16-character strings. val string: string -> t Return the digest of the given string. val substring: string -> int -> int -> t Digest.substring s ofs len returns the digest of the substring of s starting at character number ofs and containing len characters. val channel: in_channel -> int -> t Digest.channel ic len reads len characters from channel ic and returns their digest. val file: string -> t Return the digest of the file whose name is given. val output: out_channel -> t -> unit Write a digest on the given output channel. val input: in_channel -> t Read a digest from the given input channel. 15.5 Module Filename: operations on file names val current_dir_name : string The conventional name for the current directory (e.g. . in Unix). val concat : string -> string -> string concat dir file returns a file name that designates file file in directory dir. Chapter 15. The standard library 133 val is_absolute : string -> bool Return true if the file name is absolute or starts with an explicit reference to the current directory (./ or ../ in Unix), and false if it is relative to the current directory. val check_suffix : string -> string -> bool check_suffix name suff returns true if the filename name ends with the suffix suff. val chop_suffix : string -> string -> string chop_suffix name suff removes the suffix suff from the filename name. The behavior is undefined if name does not end with the suffix suff. val chop_extension : string -> string Return the given file name without its extension. An extension is a suffix starting with a period, .xyz for instance. Raise Invalid_argument if the given name does not contain a period. val basename : string -> string val dirname : string -> string Split a file name into directory name / base file name. concat (dirname name) (basename name) returns a file name which is equivalent to name. Moreover, after setting the current directory to dirname name (with Sys.chdir), references to basename name (which is a relative file name) designate the same file as name before the call to chdir. val temp_file: string -> string -> string temp_file prefix suffix returns the name of a non-existent temporary file in the temporary directory. The temporary directory is /tmp by default; if set, the value of the environment variable TMPDIR is used instead. The base name of the temporary file is formed by concatenating prefix, then a suitably chosen integer number, then suffix. 15.6 Module Format: pretty printing This module implements a pretty-printing facility to format text within ``pretty-printing boxes''. The pretty-printer breaks lines at specified break hints, and indents lines according to the box structure. Rule of thumb for casual users: use simple boxes (as obtained by open_box 0); use simple break hints (as obtained by print_cut () or by print_space () that ouputs a space); once a box is opened, display material with basic printing functions (e. g. print_int and print_string); when the material for a box has been printed, call close_box () to close the box; at the end of your routine, evaluate print_newline () to close all remaining boxes and flush the pretty-printer. Chapter 15. The standard library 134 The behaviour of pretty-printing commands is unspecified if there is no opened pretty-printing box. Each box opened via one of the open_ functions below must be closed using close_box for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. In case of interactive use, the system closes all opened boxes and flushes all pending text (as with the print_newline function) after each phrase. Each phrase is therefore executed in the initial state of the pretty-printer. Boxes val open_hbox : unit -> unit open_hbox () opens a new pretty-printing box. This box is ``horizontal'': the line is not split in this box (new lines may still occur inside boxes nested deeper). val open_vbox : int -> unit open_vbox d opens a new pretty-printing box with offset d. This box is ``vertical'': every break hint inside this box leads to a new line. When a new line is printed in the box, d is added to the current indentation. val open_hvbox : int -> unit open_hovbox d opens a new pretty-printing box with offset d. This box is ``horizontal-vertical'': it behaves as an ``horizontal'' box if it fits on a single line, otherwise it behaves as a ``vertical'' box. When a new line is printed in the box, d is added to the current indentation. val open_hovbox : int -> unit open_hovbox d opens a new pretty-printing box with offset d. This box is ``horizontal or vertical'': break hints inside this box may lead to a new line, if there is no more room on the line to print the remainder of the box. When a new line is printed in the box, d is added to the current indentation. val open_box : int -> unit open_box d opens a new pretty-printing box with offset d. This box is the general purpose pretty-printing box. Material in this box is displayed ``horizontal or vertical'': break hints inside the box may lead to a new line, if there is no more room on the line to print the remainder of the box, or if a new line may lead to a new indentation (demonstrating the indentation of the box). When a new line is printed in the box, d is added to the current indentation. val close_box : unit -> unit Close the most recently opened pretty-printing box. Chapter 15. The standard library 135 Formatting functions val print_string : string -> unit print_string str prints str in the current box. val print_as : int -> string -> unit print_as len str prints str in the current box. The pretty-printer formats str as if it were of length len. val print_int : int -> unit Print an integer in the current box. val print_float : float -> unit Print a floating point number in the current box. val print_char : char -> unit Print a character in the current box. val print_bool : bool -> unit Print an boolean in the current box. Break hints val print_break : int -> int -> unit Insert a break hint in a pretty-printing box. print_break nspaces offset indicates that the line may be split (a newline character is printed) at this point, if the contents of the current box does not fit on one line. If the line is split at that point, offset is added to the current indentation. If the line is not split, nspaces spaces are printed. val print_cut : unit -> unit print_cut () is equivalent to print_break 0 0. This allows line splitting at the current point, without printing spaces or adding indentation. val print_space : unit -> unit print_space () is equivalent to print_break 1 0. This either prints one space or splits the line at that point. val force_newline : unit -> unit Force a newline in the current box. val print_flush : unit -> unit Flush the pretty printer: all opened boxes are closed, and all pending text is displayed. Chapter 15. The standard library 136 val print_newline : unit -> unit Equivalent to print_flush followed by a new line. val print_if_newline : unit -> unit Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. Tabulations val open_tbox : unit -> unit Open a tabulation box. val close_tbox : unit -> unit Close the most recently opened tabulation box. val print_tbreak : int -> int -> unit Break hint in a tabulation box. print_tbreak spaces offset moves the insertion point to the next tabulation (spaces being added to this position). Nothing occurs if insertion point is already on a tabulation mark. If there is no next tabulation on the line, then a newline is printed and the insertion point moves to the first tabulation of the box. If a new line is printed, offset is added to the current indentation. val set_tab : unit -> unit Set a tabulation mark at the current insertion point. val print_tab : unit -> unit print_tab () is equivalent to print_tbreak (0,0). Margin val set_margin : int -> unit set_margin d sets the value of the right margin to d (in characters): this value is used to detect line overflows that leads to split lines. Nothing happens if d is smaller than 2 or bigger than 999999999. val get_margin : unit -> int Return the position of the right margin. Maximum indentation limit val set_max_indent : int -> unit set_max_indent d sets the value of the maximum indentation limit to d (in characters): once this limit is reached, boxes are rejected to the left, Chapter 15. The standard library 137 if they do not fit on the current line. Nothing happens if d is smaller than 2 or bigger than 999999999. val get_max_indent : unit -> int Return the value of the maximum indentation limit (in characters). Formatting depth: maximum number of boxes allowed before ellipsis val set_max_boxes : int -> unit set_max_boxes max sets the maximum number of boxes simultaneously opened. Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by get_ellipsis_text ()). Nothing happens if max is not greater than 1. val get_max_boxes : unit -> int Return the maximum number of boxes allowed before ellipsis. Ellipsis val set_ellipsis_text : string -> unit Set the text of the ellipsis printed when too many boxes are opened (a single dot, ., by default). val get_ellipsis_text : unit -> string Return the text of the ellipsis. Redirecting formatter output val set_formatter_out_channel : out_channel -> unit Redirect the pretty-printer output to the given channel. val set_formatter_output_functions : (string -> int -> int -> unit) -> (unit -> unit) -> unit;; set_formatter_output_functions out flush redirects the pretty-printer output to the functions out and flush. The out function performs the pretty-printer output. It is called with a string s, a start position p, and a number of characters n; it is supposed to output characters p to p+n-1 of s. The flush function is called whenever the pretty-printer is flushed using print_flush or print_newline. val get_formatter_output_functions : unit -> (string -> int -> int -> unit) * (unit -> unit);; Return the current output functions of the pretty-printer. type formatter;; Chapter 15. The standard library 138 Abstract data type corresponding to a pretty-printer and all its machinery. Defining new pretty-printers permits the output of material in parallel on several channels. Parameters of the pretty-printer are local to the prety-printer: margin, maximum indentation limit, maximum number of boxes simultaneously opened, ellipsis, and so on, are specific to each pretty-printer and may be fixed independantly. val std_formatter : formatter;; The standard formatter used by the formatting functions above. val make_formatter : (string -> int -> int -> unit) -> (unit -> unit) -> formatter;; Return a new formatter that writes according to the output functions given as argument. val pp_open_hbox : formatter -> unit -> unit;; val pp_open_vbox : formatter -> int -> unit;; val pp_open_hvbox : formatter -> int -> unit;; val pp_open_hovbox : formatter -> int -> unit;; val pp_open_box : formatter -> int -> unit;; val pp_close_box : formatter -> unit -> unit;; val pp_print_string : formatter -> string -> unit;; val pp_print_as : formatter -> int -> string -> unit;; val pp_print_int : formatter -> int -> unit;; val pp_print_float : formatter -> float -> unit;; val pp_print_char : formatter -> char -> unit;; val pp_print_bool : formatter -> bool -> unit;; val pp_print_break : formatter -> int -> int -> unit;; val pp_print_cut : formatter -> unit -> unit;; val pp_print_space : formatter -> unit -> unit;; val pp_force_newline : formatter -> unit -> unit;; val pp_print_flush : formatter -> unit -> unit;; val pp_print_newline : formatter -> unit -> unit;; val pp_print_if_newline : formatter -> unit -> unit;; val pp_open_tbox : formatter -> unit -> unit;; val pp_close_tbox : formatter -> unit -> unit;; val pp_print_tbreak : formatter -> int -> int -> unit;; val pp_set_tab : formatter -> unit -> unit;; val pp_print_tab : formatter -> unit -> unit;; val pp_set_margin : formatter -> int -> unit;; val pp_get_margin : formatter -> unit -> int;; val pp_set_max_indent : formatter -> int -> unit;; val pp_get_max_indent : formatter -> unit -> int;; val pp_set_max_boxes : formatter -> int -> unit;; val pp_get_max_boxes : formatter -> unit -> int;; val pp_set_ellipsis_text : formatter -> string -> unit;; val pp_get_ellipsis_text : formatter -> unit -> string;; val pp_set_formatter_out_channel : formatter -> out_channel -> unit;; val pp_set_formatter_output_functions : formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit;; val pp_get_formatter_output_functions : formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit);; The basic functions to use with formatters. Chapter 15. The standard library 139 15.7 Module Gc: memory management control and statistics type stat = { minor_words : int; promoted_words : int; major_words : int; minor_collections : int; major_collections : int; heap_words : int; heap_chunks : int; live_words : int; live_blocks : int; free_words : int; free_blocks : int; largest_free : int; fragments : int } The memory management counters are returned in a stat record. All the numbers are computed since the start of the program. The fields of this record are: minor_words Number of words allocated in the minor heap. promoted_words Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap. major_words Number of words allocated in the major heap, including the promoted words. minor_collections Number of minor collections. major_collections Number of major collection cycles, not counting the current cycle. heap_words Total number of words in the major heap. heap_chunks Number of times the major heap size was increased. live_words Number of words of live data in the major heap, including the header words. live_blocks Number of live objects in the major heap. free_words Number of words in the free list. free_blocks Number of objects in the free list. largest_free Size (in words) of the largest object in the free list. fragments Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live objects. They cannot be inserted in the free list, thus they are not available for allocation. The total amount of memory allocated by the program is (in words) minor_words + major_words - promoted_words. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes. type control = { mutable minor_heap_size : int; mutable major_heap_increment : int; mutable space_overhead : int; mutable verbose : bool } The GC parameters are given as a control record. The fields are: minor_heap_size The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. major_heap_increment The minimum number of words to add to the major heap when increasing it. Chapter 15. The standard library 140 space_overhead The major GC speed is computed from this parameter. This is the percentage of heap space that will be "wasted" because the GC does not immediatly collect unreachable objects. The GC will work more (use more CPU time and collect objects more eagerly) if space_overhead is smaller. The computation of the GC speed assumes that the amount of live data is constant. verbose This flag controls the GC messages on standard error output. val stat : unit -> stat Return the current values of the memory management counters in a stat record. val print_stat : out_channel -> unit Print the current values of the memory management counters (in human-readable form) into the channel argument. val get : unit -> control Return the current values of the GC parameters in a control record. val set : control -> unit set r changes the GC parameters according to the control record r. The normal usage is: let r = Gc.get () in (* Get the current parameters. *) r.verbose <- true; (* Change some of them. *) Gc.set r (* Set the new values. *) val minor : unit -> unit Trigger a minor collection. val major : unit -> unit Finish the current major collection cycle. val full_major : unit -> unit Finish the current major collection cycle and perform a complete new cycle. This will collect all currently unreachable objects. 15.8 Module Genlex: a generic lexical analyzer This module implements a simple ``standard'' lexical analyzer, presented as a function from character streams to token streams. It implements roughly the lexical conventions of Caml, but is parameterized by the set of keywords of your language. type token = Kwd of string | Ident of string Chapter 15. The standard library 141 | Int of int | Float of float | String of string | Char of char The type of tokens. The lexical classes are: Int and Float for integer and floating-point numbers; String for string literals, enclosed in double quotes; Char for character literals, enclosed in single quotes; Ident for identifiers (either sequences of letters, digits, underscores and quotes, or sequences of ``operator characters'' such as +, *, etc); and Kwd for keywords (either identifiers or single ``special characters'' such as (, }, etc). val make_lexer: string list -> (char Stream.t -> token Stream.t) Construct the lexer function. The first argument is the list of keywords. An identifier s is returned as Kwd s if s belongs to this list, and as Ident s otherwise. A special character s is returned as Kwd s if s belongs to this list, and cause a lexical error (exception Parse_error) otherwise. Blanks and newlines are skipped. Comments delimited by (* and *) are skipped as well, and can be nested. Example: a lexer suitable for a desk calculator is obtained by let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"] The associated parser would be a function from token stream to, for instance, int, and would have rules such as: let parse_expr = function [< 'Int n >] -> n | [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n | [< n1 = parse_expr; n2 = parse_remainder n1 >] -> n2 and parse_remainder n1 = function [< 'Kwd "+"; n2 = parse_expr >] -> n1+n2 | ... 15.9 Module Hashtbl: hash tables and hash functions Hash tables are hashed association tables, with in-place modification. type ('a, 'b) t The type of hash tables from type 'a to type 'b. val create : int -> ('a,'b) t Hashtbl.create n creates a new, empty hash table, with initial size n. The table grows as needed, so n is just an initial guess. Better results are said to be achieved when n is a prime number. Chapter 15. The standard library 142 val clear : ('a, 'b) t -> unit Empty a hash table. val add : ('a, 'b) t -> 'a -> 'b -> unit Hashtbl.add tbl x y adds a binding of x to y in table tbl. Previous bindings for x are not removed, but simply hidden. That is, after performing remove tbl x, the previous binding for x, if any, is restored. (This is the semantics of association lists.) val find : ('a, 'b) t -> 'a -> 'b Hashtbl.find tbl x returns the current binding of x in tbl, or raises Not_found if no such binding exists. val find_all : ('a, 'b) t -> 'a -> 'b list Hashtbl.find_all tbl x returns the list of all data associated with x in tbl. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. val remove : ('a, 'b) t -> 'a -> unit Hashtbl.remove tbl x removes the current binding of x in tbl, restoring the previous binding if it exists. It does nothing if x is not bound in tbl. val iter : ('a -> 'b -> 'c) -> ('a, 'b) t -> unit Hashtbl.iter f tbl applies f to all bindings in table tbl, discarding all the results. f receives the key as first argument, and the associated value as second argument. The order in which the bindings are passed to f is unspecified. Each binding is presented exactly once to f. The polymorphic hash primitive val hash : 'a -> int Hashtbl.hash x associates a positive integer to any value of any type. It is guaranteed that if x = y, then hash x = hash y. Moreover, hash always terminates, even on cyclic structures. val hash_param : int -> int -> 'a -> int = "hash_univ_param" "noalloc" Hashtbl.hash_param n m x computes a hash value for x, with the same properties as for hash. The two extra parameters n and m give more precise control over hashing. Hashing performs a depth-first, right-to-left traversal of the structure x, stopping after n meaningful nodes were encountered, or m nodes, meaningful or not, were encountered. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of m and n means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters m and n govern the tradeoff between accuracy and speed. Chapter 15. The standard library 143 15.10 Module Lexing: the run-time library for lexers generated by camllex Lexer buffers type lexbuf = { refill_buff : lexbuf -> unit; mutable lex_buffer : string; mutable lex_buffer_len : int; mutable lex_abs_pos : int; mutable lex_start_pos : int; mutable lex_curr_pos : int; mutable lex_last_pos : int; mutable lex_saved_state : int; mutable lex_last_action : int } The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input. val from_channel : in_channel -> lexbuf Create a lexer buffer on the given input channel. Lexing.from_channel inchan returns a lexer buffer which reads from the input channel inchan, at the current reading position. val from_string : string -> lexbuf Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached. val from_function : (string -> int -> int) -> lexbuf Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a character string s and a character count n. The function should put n characters or less in s, starting at character number 0, and return the number of characters provided. A return value of 0 means end of input. Functions for lexer semantic actions The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument lexbuf, which, in the code generated by camllex, is bound to the lexer buffer passed to the parsing function. val lexeme : lexbuf -> string Lexing.lexeme lexbuf returns the string matched by the regular expression. Chapter 15. The standard library 144 val lexeme_char : lexbuf -> int -> char Lexing.lexeme_char lexbuf i returns character number i in the matched string. val lexeme_start : lexbuf -> int Lexing.lexeme_start lexbuf returns the position in the input stream of the first character of the matched string. The first character of the stream has position 0. val lexeme_end : lexbuf -> int Lexing.lexeme_end lexbuf returns the position in the input stream of the character following the last character of the matched string. The first character of the stream has position 0. 15.11 Module List: list operations val length : 'a list -> int Return the length (number of elements) of the given list. val hd : 'a list -> 'a Return the first element of the given list. Raise Failure "hd" if the list is empty. val tl : 'a list -> 'a list Return the given list without its first element. Raise Failure "tl" if the list is empty. val nth : 'a list -> int -> 'a Return the n-th element of the given list. The first element (head of the list) is at position 0. Raise Failure "nth" if the list is too short. val rev : 'a list -> 'a list List reversal. val flatten : 'a list list -> 'a list Catenate (flatten) a list of lists. Iterators val iter : ('a -> 'b) -> 'a list -> unit List.iter f [a1; ...; an] applies function f in turn to a1; ...; an, discarding all the results. It is equivalent to begin f a1; f a2; ...; f an; () end. Chapter 15. The standard library 145 val map : ('a -> 'b) -> 'a list -> 'b list List.map f [a1; ...; an] applies function f to a1, ..., an, and builds the list [f a1; ...; f an] with the results returned by f. val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a List.fold_left f a [b1; ...; bn] is f (... (f (f a b1) b2) ...) bn. val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b List.fold_right f [a1; ...; an] b is f a1 (f a2 (... (f an b) ...)). Iterators on two lists val iter2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> unit List.iter2 f [a1; ...; an] [b1; ...; bn] calls in turn f a1 b1; ...; f an bn, discarding the results. Raise Invalid_argument if the two lists have different lengths. val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list List.map2 f [a1; ...; an] [b1; ...; bn] is [f a1 b1; ...; f an bn]. Raise Invalid_argument if the two lists have different lengths. val fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b list -> 'c list -> 'a List.fold_left2 f a [b1; ...; bn] [c1; ...; cn] is f (... (f (f a b1 c1) b2 c2) ...) bn cn. Raise Invalid_argument if the two lists have different lengths. val fold_right2 : ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c List.fold_right2 f [a1; ...; an] [b1; ...; bn] c is f a1 b1 (f a2 b2 (... (f an bn c) ...)). Raise Invalid_argument if the two lists have different lengths. List scanning val for_all : ('a -> bool) -> 'a list -> bool for_all p [a1; ...; an] checks if all elements of the list satisfy the predicate p. That is, it returns (p a1) & (p a2) & ... & (p an). val exists : ('a -> bool) -> 'a list -> bool exists p [a1; ...; an] checks if at least one element of the list satisfies the predicate p. That is, it returns (p a1) or (p a2) or ... or (p an). val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool Same as for_all and exists, but for a two-argument predicate. Raise Invalid_argument if the two lists have different lengths. Chapter 15. The standard library 146 val mem : 'a -> 'a list -> bool mem a l is true if and only if a is equal to an element of l. val memq : 'a -> 'a list -> bool Same as mem, but uses physical equality instead of structural equality to compare list elements. Association lists val assoc : 'a -> ('a * 'b) list -> 'b assoc a l returns the value associated with key a in the list of pairs l. That is, assoc a [ ...; (a,b); ...] = b if (a,b) is the leftmost binding of a in list l. Raise Not_found if there is no value associated with a in the list l. val mem_assoc : 'a -> ('a * 'b) list -> bool Same as assoc, but simply return true if a binding exists, and false if no bindings exist for the given key. val assq : 'a -> ('a * 'b) list -> 'b Same as assoc, but uses physical equality instead of structural equality to compare keys. Lists of pairs val split : ('a * 'b) list -> 'a list * 'b list Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)] is ([a1; ...; an], [b1; ...; bn]) val combine : 'a list -> 'b list -> ('a * 'b) list Transform a pair of lists into a list of pairs: combine ([a1; ...; an], [b1; ...; bn]) is [(a1,b1); ...; (an,bn)]. Raise Invalid_argument if the two lists have different lengths. 15.12 Module Map: association tables over ordered types This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. module type OrderedType = sig type t val compare: t -> t -> int end Chapter 15. The standard library 147 The input signature of the functor Map.Make. t is the type of the map keys. compare is a total ordering function over the keys. This is a two-argument function f such that f e1 e2 is zero if the keys e1 and e2 are equal, f e1 e2 is strictly negative if e1 is smaller than e2, and f e1 e2 is strictly positive if e1 is greater than e2. Examples: a suitable ordering function for type int is (-). You can also use the generic structural comparison function compare. module type S = sig type key The type of the map keys. type 'a t The type of maps from type key to type 'a. val empty: 'a t The empty map. val add: key -> 'a -> 'a t -> 'a t add x y m returns a map containing the same bindings as m, plus a binding of x to y. If x was already bound in m, its previous binding disappears. val find: key -> 'a t -> 'a find x m returns the current binding of x in m, or raises Not_found if no such binding exists. val remove: key -> 'a t -> 'a t remove x m returns a map containing the same bindings as m, except for x which is unbound in the returned map. val iter: (key -> 'a -> 'b) -> 'a t -> unit iter f m applies f to all bindings in map m, discarding the results. f receives the key as first argument, and the associated value as second argument. The order in which the bindings are passed to f is unspecified. Only current bindings are presented to f: bindings hidden by more recent bindings are not passed to f. val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b fold f m a computes (f kN dN ... (f k1 d1 a)...), where k1 ... kN are the keys of all bindings in m, and d1 ... dN are the associated data. The order in which the bindings are presented to f is not specified. end module Make(Ord: OrderedType): (S with type key = Ord.t) Functor building an implementation of the map structure given a totally ordered type. Chapter 15. The standard library 148 15.13 Module Oo: object-oriented extension val copy : (< .. > as 'a) -> 'a Oo.copy o returns a copy of object o, that is a fresh object with the same methods and instance variables as o 15.14 Module Parsing: the run-time library for parsers generated by camlyacc val symbol_start : unit -> int val symbol_end : unit -> int symbol_start and symbol_end are to be called in the action part of a grammar rule only. They return the position of the string that matches the left-hand side of the rule: symbol_start() returns the position of the first character; symbol_end() returns the position of the last character, plus one. The first character in a file is at position 0. val rhs_start: int -> int val rhs_end: int -> int Same as symbol_start and symbol_end, but return the position of the string matching the nth item on the right-hand side of the rule, where n is the integer parameter to lhs_start and lhs_end. n is 1 for the leftmost item. val clear_parser : unit -> unit Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs. exception Parse_error Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery. 15.15 Module Printexc: a catch-all exception handler val catch: ('a -> 'b) -> 'a -> 'b Printexc.catch fn x applies fn to x and returns the result. If the evaluation of fn x raises any exception, the name of the exception is printed on standard error output, and the programs aborts with exit code 2. Typical use is Printexc.catch main (), where main, with type unit->unit, is the entry point of a standalone program. This catches and reports any exception that escapes the program. val print: ('a -> 'b) -> 'a -> 'b Same as catch, but re-raise the stray exception after printing it, instead of aborting the program. Chapter 15. The standard library 149 15.16 Module Printf: formatting printing functions val fprintf: out_channel -> ('a, out_channel, unit) format -> 'a fprintf outchan format arg1 ... argN formats the arguments arg1 to argN according to the format string format, and outputs the resulting string on the channel outchan. The format is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of one argument. Conversion specifications consist in the % character, followed by optional flags and field widths, followed by one conversion character. The conversion characters and their meanings are: d or i: convert an integer argument to signed decimal u: convert an integer argument to unsigned decimal x: convert an integer argument to unsigned hexadecimal, using lowercase letters. X: convert an integer argument to unsigned hexadecimal, using uppercase letters. s: insert a string argument c: insert a character argument f: convert a floating-point argument to decimal notation, in the style dddd.ddd e or E: convert a floating-point argument to decimal notation, in the style d.ddd e+-dd (mantissa and exponent) g or G: convert a floating-point argument to decimal notation, in style f or e, E (whichever is more compact) b: convert a boolean argument to the string true or false a: user-defined printer. Takes two arguments and apply the first one to outchan (the current output channel) and to the second argument. The first argument must therefore have type out_channel -> 'b -> unit and the second 'b. The output produced by the function is therefore inserted in the output of fprintf at the current point. t: same as %a, but takes only one argument (with type out_channel -> unit) and apply it to outchan. Refer to the C library printf function for the meaning of flags and field width specifiers. If too few arguments are provided, printing stops just before converting the first missing argument. val printf: ('a, out_channel, unit) format -> 'a Same as fprintf, but output on stdout. val eprintf: ('a, out_channel, unit) format -> 'a Same as fprintf, but output on stderr. val sprintf: ('a, unit, string) format -> 'a Same as printf, but return the result of formatting in a string. Chapter 15. The standard library 150 15.17 Module Queue: first-in first-out queues This module implements queues (FIFOs), with in-place modification. type 'a t The type of queues containing elements of type 'a. exception Empty Raised when take is applied to an empty queue. val create: unit -> 'a t Return a new queue, initially empty. val add: 'a -> 'a t -> unit add x q adds the element x at the end of the queue q. val take: 'a t -> 'a take q removes and returns the first element in queue q, or raises Empty if the queue is empty. val peek: 'a t -> 'a peek q returns the first element in queue q, without removing it from the queue, or raises Empty if the queue is empty. val clear : 'a t -> unit Discard all elements from a queue. val length: 'a t -> int Return the number of elements in a queue. val iter: ('a -> 'b) -> 'a t -> unit iter f q applies f in turn to all elements of q, from the least recently entered to the most recently entered. The queue itself is unchanged. 15.18 Module Random: pseudo-random number generator val init : int -> unit Initialize the generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. val full_init : int array -> unit Same as init but takes more data as seed. It is not useful to give more than 55 integers. Chapter 15. The standard library 151 val int : int -> int Random.int bound returns a random number between 0 (inclusive) and bound 30 (exclusive). bound must be positive and smaller than 2 . val float : float -> float Random.float bound returns a random number between 0 (inclusive) and bound (exclusive). 15.19 Module Set: sets over ordered types This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. module type OrderedType = sig type t val compare: t -> t -> int end The input signature of the functor Set.Make. t is the type of the set elements. compare is a total ordering function over the set elements. This is a two-argument function f such that f e1 e2 is zero if the elements e1 and e2 are equal, f e1 e2 is strictly negative if e1 is smaller than e2, and f e1 e2 is strictly positive if e1 is greater than e2. Examples: a suitable ordering function for type int is (-). You can also use the generic structural comparison function compare. module type S = sig type elt The type of the set elements. type t The type of sets. val empty: t The empty set. val is_empty: t -> bool Test whether a set is empty or not. val mem: elt -> t -> bool mem x s tests whether x belongs to the set s. Chapter 15. The standard library 152 val add: elt -> t -> t add x s returns a set containing all elements of s, plus x. If x was already in s, s is returned unchanged. val remove: elt -> t -> t remove x s returns a set containing all elements of s, except x. If x was not in s, s is returned unchanged. val union: t -> t -> t val inter: t -> t -> t val diff: t -> t -> t Union, intersection and set difference. val compare: t -> t -> int Total ordering between sets. Can be used as the ordering function for doing sets of sets. val equal: t -> t -> bool equal s1 s2 tests whether the sets s1 and s2 are equal, that is, contain the same elements. val iter: (elt -> 'a) -> t -> unit iter f s applies f in turn to all elements of s, and discards the results. The elements of s are presented to f in a non-specified order. val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a fold f s a computes (f xN ... (f x2 (f x1 a))...), where x1 ... xN are the elements of s. The order in which elements of s are presented to f is not specified. val cardinal: t -> int Return the number of elements of a set. val elements: t -> elt list Return the list of all elements of the given set. The elements appear in the list in some non-specified order. val choose: t -> elt Return one element of the given set, or raise Not_found if the set is empty. Which element is chosen is not specified, but equal elements will be chosen for equal sets. end module Make(Ord: OrderedType): (S with type elt = Ord.t) Functor building an implementation of the set structure given a totally ordered type. Chapter 15. The standard library 153 15.20 Module Sort: sorting and merging lists val list : ('a -> 'a -> bool) -> 'a list -> 'a list Sort a list in increasing order according to an ordering predicate. The predicate should return true if its first argument is less than or equal to its second argument. val merge : ('a -> 'a -> bool) -> 'a list -> 'a list -> 'a list Merge two lists according to the given predicate. Assuming the two argument lists are sorted according to the predicate, merge returns a sorted list containing the elements from the two lists. The behavior is undefined if the two argument lists were not sorted. 15.21 Module Stack: last-in first-out stacks This module implements stacks (LIFOs), with in-place modification. type 'a t The type of stacks containing elements of type 'a. exception Empty Raised when pop is applied to an empty stack. val create: unit -> 'a t Return a new stack, initially empty. val push: 'a -> 'a t -> unit push x s adds the element x at the top of stack s. val pop: 'a t -> 'a pop s removes and returns the topmost element in stack s, or raises Empty if the stack is empty. val clear : 'a t -> unit Discard all elements from a stack. val length: 'a t -> int Return the number of elements in a stack. val iter: ('a -> 'b) -> 'a t -> unit iter f s applies f in turn to all elements of s, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged. Chapter 15. The standard library 154 15.22 Module Stream: streams and stream parsers operations type 'a t The type of streams containing values of type 'a. exception Parse_failure Raised by parsers when none of the first components of the stream patterns is accepted. exception Parse_error of string Raised by parsers when the first component of a stream pattern is accepted, but one of the following components is rejected. Stream builders Warning: these functions create streams with fast access; it is illegal to mix them with streams built with [< >]; would raise Failure when accessing such mixed streams. val from : (int -> 'a option) -> 'a t Stream.from f returns a stream built from the function f. To create a new stream element, the function f is called with the current stream count. The user function f must return either Some for a value or None to specify the end of the stream. val of_list : 'a list -> 'a t Return the stream holding the elements of the list in the same order. val of_string : string -> char t Return the stream of the characters of the string parameter. val of_channel : in_channel -> char t Return the stream of the characters read from the input channel. Stream iterator val iter : ('a -> 'b) -> 'a t -> unit Stream.iter f s scans the whole stream s, applying function f in turn to each stream element encountered. Predefined parsers val next : 'a t -> 'a Return the first element of the stream and remove it from the stream. Raise Parse_failure if the stream is empty. Chapter 15. The standard library 155 val empty : 'a t -> unit Return () if the stream is empty, else raise Parse_failure. Useful functions val peek : 'a t -> 'a option Return Some c where c is the first element of the stream, or None if the stream is empty. val junk : 'a t -> unit Remove the first element of the stream, possibly unfreezing it before. val count : 'a t -> int Return the current count of the stream elements, i.e. the number of the stream elements discarded. 15.23 Module String: string operations val length : string -> int Return the length (number of characters) of the given string. val get : string -> int -> char String.get s n returns character number n in string s. The first character is character number 0. The last character is character number String.length s - 1. Raise Invalid_argument if n is ouside the range 0 to (String.length s - 1). You can also write s.[n] instead of String.get s n. val set : string -> int -> char -> unit String.set s n c modifies string s in place, replacing the character number n by c. Raise Invalid_argument if n is ouside the range 0 to (String.length s - 1). You can also write s.[n] <- c instead of String.set s n c. val create : int -> string String.create n returns a fresh string of length n. The string initially contains arbitrary characters. val make : int -> char -> string String.make n c returns a fresh string of length n, filled with the character c. val copy : string -> string Return a copy of the given string. Chapter 15. The standard library 156 val sub : string -> int -> int -> string String.sub s start len returns a fresh string of length len, containing the characters number start to start + len - 1 of string s. Raise Invalid_argument if start and len do not designate a valid substring of s; that is, if start < 0, or len < 0, or start + len > String.length s. val fill : string -> int -> int -> char -> unit String.fill s start len c modifies string s in place, replacing the characters number start to start + len - 1 by c. Raise Invalid_argument if start and len do not designate a valid substring of s. val blit : string -> int -> string -> int -> int -> unit String.blit s1 o1 s2 o2 len copies len characters from string s1, starting at character number o1, to string s2, starting at character number o2. It works correctly even if s1 and s2 are the same string, and the source and destination chunks overlap. Raise Invalid_argument if o1 and len do not designate a valid substring of s1, or if o2 and len do not designate a valid substring of s2. val concat : string -> string list -> string String.concat sep sl catenates the list of strings sl, inserting the separator string sep between each. val escaped: string -> string Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of Caml Light. 15.24 Module Sys: system interface val argv: string array The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the arguments given to the program. val file_exists: string -> bool Test if a file with the given name exists. val remove: string -> unit Remove the given file name from the file system. val rename : string -> string -> unit Rename a file. The first argument is the old name and the second is the new name. val getenv: string -> string Chapter 15. The standard library 157 Return the value associated to a variable in the process environment. Raise Not_found if the variable is unbound. val command: string -> int Execute the given shell command and return its exit code. val chdir: string -> unit Change the current working directory of the process. val getcwd: unit -> string Return the current working directory of the process. val interactive: bool ref This reference is initially set to false in standalone programs and to true if the code is being executed under the interactive toplevel csltop. Signal handling type signal_behavior = Signal_default | Signal_ignore | Signal_handle of (int -> unit) What to do when receiving a signal: Signal_default: take the default behavior Signal_ignore: ignore the signal Signal_handle f: call function f, giving it the signal number as argument. val signal: int -> signal_behavior -> unit Set the behavior of the system on receipt of a given signal. The first argument is the signal number. val sigabrt: int (* Abnormal termination *) val sigalrm: int (* Timeout *) val sigfpe: int (* Arithmetic exception *) val sighup: int (* Hangup on controlling terminal *) val sigill: int (* Invalid hardware instruction *) val sigint: int (* Interactive interrupt (ctrl-C) *) val sigkill: int (* Termination (cannot be ignored) *) val sigpipe: int (* Broken pipe *) val sigquit: int (* Interactive termination *) val sigsegv: int (* Invalid memory reference *) val sigterm: int (* Termination *) val sigusr1: int (* Application-defined signal 1 *) val sigusr2: int (* Application-defined signal 2 *) val sigchld: int (* Child process terminated *) val sigcont: int (* Continue *) val sigstop: int (* Stop *) val sigtstp: int (* Interactive stop *) val sigttin: int (* Terminal read from background process *) val sigttou: int (* Terminal write from background process *) Chapter 15. The standard library 158 val sigvtalrm: int (* Timeout in virtual time *) val sigprof: int (* Profiling interrupt *) Signal numbers for the standard POSIX signals. exception Break Exception raised on interactive interrupt if catch_break is on. val catch_break: bool -> unit catch_break governs whether interactive interrupt (ctrl-C) terminates the program or raises the Break exception. Call catch_break true to enable raising Break, and catch_break false to let the system terminate the program on user interrupt. Chapter 16 The unix library: Unix system calls The unix library makes many Unix system calls and system-related library functions available to Objective Caml programs. This chapter describes briefly the functions provided. Refer to sections 2 and 3 of the Unix manual for more details on the behavior of these functions. Not all functions are provided by all Unix variants. If some functions are not available, they will raise Invalid_arg when called. Unix: Programs that use the unix library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options unix.cma other files -cclib -lunix ocamlopt other options unix.cmxa other files -cclib -lunix For interactive use of the unix library, do: ocamlmktop -custom -o mytop unix.cma -cclib -lunix ./mytop Windows: A fairly complete emulation of the Unix system calls is provided in the Windows version of Objective Caml. The end of this chapter gives more information on the functions that are not supported under Windows. Programs that use the unix library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options unix.cma other files \ %CAMLLIB%/libunix.lib wsock32.lib ocamlopt other options unix.cmxa other files \ %CAMLLIB%/libunix.lib wsock32.lib For interactive use of the unix library, do: ocamlmktop -custom -o mytop.exe unix.cma \ %CAMLLIB%/libunix.lib wsock32.lib 159 Chapter 16. The unix library: Unix system calls 160 mytop.exe 16.1 Module Unix: interface to the Unix system Error report type error = Errors defined in the POSIX standard E2BIG (* Argument list too long *) | EACCESS (* Permission denied *) | EAGAIN (* Resource temporarily unavailable; try again *) | EBADF (* Bad file descriptor *) | EBUSY (* Resource unavailable *) | ECHILD (* No child process *) | EDEADLK (* Resource deadlock would occur *) | EDOM (* Domain error for math functions, etc. *) | EEXIST (* File exists *) | EFAULT (* Bad address *) | EFBIG (* File too large *) | EINTR (* Function interrupted by signal *) | EINVAL (* Invalid argument *) | EIO (* Hardware I/O error *) | EISDIR (* Is a directory *) | EMFILE (* Too many open files by the process *) | EMLINK (* Too many links *) | ENAMETOOLONG (* Filename too long *) | ENFILE (* Too many open files in the system *) | ENODEV (* No such device *) | ENOENT (* No such file or directory *) | ENOEXEC (* Not an executable file *) | ENOLCK (* No locks available *) | ENOMEM (* Not enough memory *) | ENOSPC (* No space left on device *) | ENOSYS (* Function not supported *) | ENOTDIR (* Not a directory *) | ENOTEMPTY (* Directory not empty *) | ENOTTY (* Inappropriate I/O control operation *) | ENXIO (* No such device or address *) | EPERM (* Operation not permitted *) | EPIPE (* Broken pipe *) | ERANGE (* Result too large *) | EROFS (* Read-only file system *) | ESPIPE (* Invalid seek e.g. on a pipe *) | ESRCH (* No such process *) | EXDEV (* Invalid link *) Additional errors, mostly BSD | EWOULDBLOCK (* Operation would block *) | EINPROGRESS (* Operation now in progress *) | EALREADY (* Operation already in progress *) | ENOTSOCK (* Socket operation on non-socket *) | EDESTADDRREQ (* Destination address required *) | EMSGSIZE (* Message too long *) Chapter 16. The unix library: Unix system calls 161 | EPROTOTYPE (* Protocol wrong type for socket *) | ENOPROTOOPT (* Protocol not available *) | EPROTONOSUPPORT (* Protocol not supported *) | ESOCKTNOSUPPORT (* Socket type not supported *) | EOPNOTSUPP (* Operation not supported on socket *) | EPFNOSUPPORT (* Protocol family not supported *) | EAFNOSUPPORT (* Address family not supported by protocol family *) | EADDRINUSE (* Address already in use *) | EADDRNOTAVAIL (* Can't assign requested address *) | ENETDOWN (* Network is down *) | ENETUNREACH (* Network is unreachable *) | ENETRESET (* Network dropped connection on reset *) | ECONNABORTED (* Software caused connection abort *) | ECONNRESET (* Connection reset by peer *) | ENOBUFS (* No buffer space available *) | EISCONN (* Socket is already connected *) | ENOTCONN (* Socket is not connected *) | ESHUTDOWN (* Can't send after socket shutdown *) | ETOOMANYREFS (* Too many references: can't splice *) | ETIMEDOUT (* Connection timed out *) | ECONNREFUSED (* Connection refused *) | EHOSTDOWN (* Host is down *) | EHOSTUNREACH (* No route to host *) | ELOOP (* Too many levels of symbolic links *) All other errors are mapped to EUNKNOWNERR | EUNKNOWNERR (* Unknown error *) The type of error codes. exception Unix_error of error * string * string Raised by the system calls below when an error is encountered. The first component is the error code; the second component is the function name; the third component is the string parameter to the function, if it has one, or the empty string otherwise. val error_message : error -> string Return a string describing the given error code. val handle_unix_error : ('a -> 'b) -> 'a -> 'b handle_unix_error f x applies f to x and returns the result. If the exception Unix_error is raised, it prints a message describing the error and exits with code 2. Interface with the parent process val environment : unit -> string array Return the process environment, as an array of strings with the format ``variable=value''. See also sys__getenv. Chapter 16. The unix library: Unix system calls 162 Process handling type process_status = WEXITED of int | WSIGNALED of int | WSTOPPED of int The termination status of a process. WEXITED means that the process terminated normally by exit; the argument is the return code. WSIGNALED means that the process was killed by a signal; the argument is the signal number. WSTOPPED means that the process was stopped by a signal; the argument is the signal number. type wait_flag = WNOHANG | WUNTRACED Flags for waitopt and waitpid. WNOHANG means do not block if no child has died yet, but immediately return with a pid equal to 0. WUNTRACED means report also the children that receive stop signals. val execv : string -> string array -> unit execv prog args execute the program in file prog, with the arguments args, and the current process environment. val execve : string -> string array -> string array -> unit Same as execv, except that the third argument provides the environment to the program executed. val execvp : string -> string array -> unit val execvpe : string -> string array -> string array -> unit Same as execv and execvp respectively, except that the program is searched in the path. val fork : unit -> int Fork a new process. The returned integer is 0 for the child process, the pid of the child process for the parent process. val wait : unit -> int * process_status Wait until one of the children processes die, and return its pid and termination status. val waitpid : wait_flag list -> int -> int * process_status Same as wait, but waits for the process whose pid is given. A pid of -1 means wait for any child. A pid of 0 means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. The list of options indicates whether waitpid should return immediately without waiting, or also report stopped children. Chapter 16. The unix library: Unix system calls 163 val system : string -> process_status Execute the given command, wait until it terminates, and return its termination status. The string is interpreted by the shell /bin/sh and therefore can contain redirections, quotes, variables, etc. The result WEXITED 127 indicates that the shell couldn't be executed. val getpid : unit -> int Return the pid of the process. val getppid : unit -> int Return the pid of the parent process. val nice : int -> int Change the process priority. The integer argument is added to the ``nice'' value. (Higher values of the ``nice'' value mean lower priorities.) Return the new nice value. Basic file input/output type file_descr The abstract type of file descriptors. val stdin : file_descr val stdout : file_descr val stderr : file_descr File descriptors for standard input, standard output and standard error. type open_flag = O_RDONLY (* Open for reading *) | O_WRONLY (* Open for writing *) | O_RDWR (* Open for reading and writing *) | O_NONBLOCK (* Open in non-blocking mode *) | O_APPEND (* Open for append *) | O_CREAT (* Create if nonexistent *) | O_TRUNC (* Truncate to 0 length if existing *) | O_EXCL (* Fail if existing *) The flags to open. type file_perm = int The type of file access rights. val openfile : string -> open_flag list -> file_perm -> file_descr Open the named file with the given flags. Third argument is the permissions to give to the file if it is created. Return a file descriptor on the named file. Chapter 16. The unix library: Unix system calls 164 val close : file_descr -> unit Close a file descriptor. val read : file_descr -> string -> int -> int -> int read fd buff ofs len reads len characters from descriptor fd, storing them in string buff, starting at position ofs in string buff. Return the number of characters actually read. val write : file_descr -> string -> int -> int -> int write fd buff ofs len writes len characters to descriptor fd, taking them from string buff, starting at position ofs in string buff. Return the number of characters actually written. Interfacing with the standard input/output library. val in_channel_of_descr : file_descr -> in_channel Create an input channel reading from the given descriptor. val out_channel_of_descr : file_descr -> out_channel Create an output channel writing on the given descriptor. val descr_of_in_channel : in_channel -> file_descr Return the descriptor corresponding to an input channel. val descr_of_out_channel : out_channel -> file_descr Return the descriptor corresponding to an output channel. Seeking and truncating type seek_command = SEEK_SET | SEEK_CUR | SEEK_END Positioning modes for lseek. SEEK_SET indicates positions relative to the beginning of the file, SEEK_CUR relative to the current position, SEEK_END relative to the end of the file. val lseek : file_descr -> int -> seek_command -> int Set the current position for a file descriptor val truncate : string -> int -> unit Truncates the named file to the given size. val ftruncate : file_descr -> int -> unit Chapter 16. The unix library: Unix system calls 165 Truncates the file corresponding to the given descriptor to the given size. File statistics type file_kind = S_REG (* Regular file *) | S_DIR (* Directory *) | S_CHR (* Character device *) | S_BLK (* Block device *) | S_LNK (* Symbolic link *) | S_FIFO (* Named pipe *) | S_SOCK (* Socket *) type stats = { st_dev : int; (* Device number *) st_ino : int; (* Inode number *) st_kind : file_kind; (* Kind of the file *) st_perm : file_perm; (* Access rights *) st_nlink : int; (* Number of links *) st_uid : int; (* User id of the owner *) st_gid : int; (* Group id of the owner *) st_rdev : int; (* Device minor number *) st_size : int; (* Size in bytes *) st_atime : int; (* Last access time *) st_mtime : int; (* Last modification time *) st_ctime : int } (* Last status change time *) The informations returned by the stat calls. val stat : string -> stats Return the information for the named file. val lstat : string -> stats Same as stat, but in case the file is a symbolic link, return the information for the link itself. val fstat : file_descr -> stats Return the information for the file associated with the given descriptor. Operations on file names val unlink : string -> unit Removes the named file val rename : string -> string -> unit rename old new changes the name of a file from old to new. val link : string -> string -> unit link source dest creates a hard link named dest to the file named new. Chapter 16. The unix library: Unix system calls 166 File permissions and ownership type access_permission = R_OK (* Read permission *) | W_OK (* Write permission *) | X_OK (* Execution permission *) | F_OK (* File exists *) Flags for the access call. val chmod : string -> file_perm -> unit Change the permissions of the named file. val fchmod : file_descr -> file_perm -> unit Change the permissions of an opened file. val chown : string -> int -> int -> unit Change the owner uid and owner gid of the named file. val fchown : file_descr -> int -> int -> unit Change the owner uid and owner gid of an opened file. val umask : int -> int Set the process creation mask, and return the previous mask. val access : string -> access_permission list -> unit Check that the process has the given permissions over the named file. Raise Unix_error otherwise. Operations on file descriptors val dup : file_descr -> file_descr Return a new file descriptor referencing the same file as the given descriptor. val dup2 : file_descr -> file_descr -> unit dup2 fd1 fd2 duplicates fd1 to fd2, closing fd2 if already opened. val set_nonblock : file_descr -> unit val clear_nonblock : file_descr -> unit Set or clear the ``non-blocking'' flag on the given descriptor. When the non-blocking flag is set, reading on a descriptor on which there is temporarily no data available raises the EAGAIN or EWOULDBLOCK error instead of blocking; writing on a descriptor on which there is temporarily no room for writing also raises EAGAIN or EWOULDBLOCK. Chapter 16. The unix library: Unix system calls 167 val set_close_on_exec : file_descr -> unit val clear_close_on_exec : file_descr -> unit Set or clear the ``close-on-exec'' flag on the given descriptor. A descriptor with the close-on-exec flag is automatically closed when the current process starts another program with one of the exec functions. Directories val mkdir : string -> file_perm -> unit Create a directory with the given permissions. val rmdir : string -> unit Remove an empty directory. val chdir : string -> unit Change the process working directory. val getcwd : unit -> string Return the name of the current working directory. type dir_handle The type of descriptors over opened directories. val opendir : string -> dir_handle Open a descriptor on a directory val readdir : dir_handle -> string Return the next entry in a directory. Raise End_of_file when the end of the directory has been reached. val rewinddir : dir_handle -> unit Reposition the descriptor to the beginning of the directory val closedir : dir_handle -> unit Close a directory descriptor. Pipes and redirections val pipe : unit -> file_descr * file_descr Create a pipe. The first component of the result is opened for reading, that's the exit to the pipe. The second component is opened for writing, that's the entrance to the pipe. Chapter 16. The unix library: Unix system calls 168 val mkfifo : string -> file_perm -> unit Create a named pipe with the given permissions. High-level process and redirection management val create_process : string -> string array -> file_descr -> file_descr -> file_descr -> int create_process prog args new_stdin new_stdout new_stderr forks a new process that executes the program in file prog, with arguments args. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The standard input and outputs of the new process are connected to the descriptors new_stdin, new_stdout and new_stderr. Passing e.g. stdout for new_stdout prevents the redirection and causes the new process to have the same standard output as the current process. The executable file prog is searched in the path. The new process has the same environment as the current process. All file descriptors of the current process are closed in the new process, except those redirected to standard input and outputs. val create_process_env : string -> string array -> string array -> file_descr -> file_descr -> file_descr -> int create_process_env prog args env new_stdin new_stdout new_stderr works as create_process, except that the extra argument env specifies the environment passed to the program. val open_process_in: string -> in_channel val open_process_out: string -> out_channel val open_process: string -> in_channel * out_channel High-level pipe and process management. These functions run the given command in parallel with the program, and return channels connected to the standard input and/or the standard output of the command. The command is interpreted by the shell /bin/sh (cf. system). Warning: writes on channels are buffered, hence be careful to call flush at the right times to ensure correct synchronization. val close_process_in: in_channel -> process_status val close_process_out: out_channel -> process_status val close_process: in_channel * out_channel -> process_status Close channels opened by open_process_in, open_process_out and open_process, respectively, wait for the associated command to terminate, and return its termination status. Symbolic links val symlink : string -> string -> unit symlink source dest creates the file dest as a symbolic link to the file source. Chapter 16. The unix library: Unix system calls 169 val readlink : string -> string Read the contents of a link. Special files val ioctl_int : file_descr -> int -> int -> int Interface to ioctl in the case where the argument is an integer. The first integer argument is the command code; the second is the integer parameter. val ioctl_ptr : file_descr -> int -> string -> int Interface to ioctl in the case where the argument is a pointer. The integer argument is the command code. A pointer to the string argument is passed as argument to the command. Polling val select : file_descr list -> file_descr list -> file_descr list -> float -> file_descr list * file_descr list * file_descr list Wait until some input/output operations become possible on some channels. The three list arguments are, respectively, a set of descriptors to check for reading (first argument), for writing (second argument), or for exceptional conditions (third argument). The fourth argument is the maximal timeout, in seconds; a negative fourth argument means no timeout (unbounded wait). The result is composed of three sets of descriptors: those ready for reading (first component), ready for writing (second component), and over which an exceptional condition is pending (third component). Locking type lock_command = F_ULOCK (* Unlock a region *) | F_LOCK (* Lock a region, and block if already locked *) | F_TLOCK (* Lock a region, or fail if already locked *) | F_TEST (* Test a region for other process' locks *) Commands for lockf. val lockf : file_descr -> lock_command -> int -> unit lockf fd cmd size puts a lock on a region of the file opened as fd. The region starts at the current read/write position for fd (as set by lseek), and extends size bytes forward if size is positive, size bytes backwards if size is negative, or to the end of the file if size is zero. Chapter 16. The unix library: Unix system calls 170 Signals val kill : int -> int -> unit kill pid sig sends signal number sig to the process with id pid. val pause : unit -> unit Wait until a non-ignored signal is delivered. Time functions type process_times = { tms_utime : float; (* User time for the process *) tms_stime : float; (* System time for the process *) tms_cutime : float; (* User time for the children processes *) tms_cstime : float } (* System time for the children processes *) The execution times (CPU times) of a process. type tm = { tm_sec : int; (* Seconds 0..59 *) tm_min : int; (* Minutes 0..59 *) tm_hour : int; (* Hours 0..23 *) tm_mday : int; (* Day of month 1..31 *) tm_mon : int; (* Month of year 0..11 *) tm_year : int; (* Year - 1900 *) tm_wday : int; (* Day of week (Sunday is 0) *) tm_yday : int; (* Day of year 0..365 *) tm_isdst : bool } (* Daylight time savings in effect *) The type representing wallclock time and calendar date. val time : unit -> int Return the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds. val gettimeofday : unit -> float Same as time, but with resolution better than 1 second. val gmtime : int -> tm Convert a time in seconds, as returned by time, into a date and a time. Assumes Greenwich meridian time zone. val localtime : int -> tm Convert a time in seconds, as returned by time, into a date and a time. Assumes the local time zone. val mktime : tm -> int * tm Convert a date and time, specified by the tm argument, into a time in seconds, as returned by time. Also return a normalized copy of the given tm record, with the tm_wday and tm_yday recomputed from the other fields. Chapter 16. The unix library: Unix system calls 171 val alarm : int -> int Schedule a SIGALRM signals after the given number of seconds. val sleep : int -> unit Stop execution for the given number of seconds. val times : unit -> process_times = "unix_times_bytecode" "unix_times_native" Return the execution times of the process. val utimes : string -> int -> int -> unit Set the last access time (second arg) and last modification time (third arg) for a file. Times are expressed in seconds from 00:00:00 GMT, Jan. 1, 1970. type interval_timer = ITIMER_REAL | ITIMER_VIRTUAL | ITIMER_PROF The three kinds of interval timers. ITIMER_REAL decrements in real time, and sends the signal SIGALRM when expired. ITIMER_VIRTUAL decrements in process virtual time, and sends SIGVTALRM when expired. ITIMER_PROF (for profiling) decrements both when the process is running and when the system is running on behalf of the process; it sends SIGPROF when expired. type interval_timer_status = { it_interval: float; (* Period *) it_value: float } (* Current value of the timer *) The type describing the status of an interval timer val getitimer: interval_timer -> interval_timer_status = "unix_getitimer" "unix_getitimer_native" Return the current status of the given interval timer. val setitimer: interval_timer -> interval_timer_status -> interval_timer_status = "unix_setitimer" "unix_setitimer_native" setitimer t s sets the interval timer t and returns its previous status. The s argument is interpreted as follows: s.it_value, if nonzero, is the time to the next timer expiration; s.it_interval, if nonzero, specifies a value to be used in reloading it_value when the timer expires. Setting s.it_value to zero disable the timer. Setting s.it_interval to zero causes the timer to be disabled after its next expiration. User id, group id val getuid : unit -> int Chapter 16. The unix library: Unix system calls 172 Return the user id of the user executing the process. val geteuid : unit -> int Return the effective user id under which the process runs. val setuid : int -> unit Set the real user id and effective user id for the process. val getgid : unit -> int Return the group id of the user executing the process. val getegid : unit -> int Return the effective group id under which the process runs. val setgid : int -> unit Set the real group id and effective group id for the process. val getgroups : unit -> int array Return the list of groups to which the user executing the process belongs. type passwd_entry = { pw_name : string; pw_passwd : string; pw_uid : int; pw_gid : int; pw_gecos : string; pw_dir : string; pw_shell : string } Structure of entries in the passwd database. type group_entry = { gr_name : string; gr_passwd : string; gr_gid : int; gr_mem : string array } Structure of entries in the groups database. val getlogin : unit -> string Return the login name of the user executing the process. val getpwnam : string -> passwd_entry Find an entry in passwd with the given name, or raise Not_found. val getgrnam : string -> group_entry Find an entry in group with the given name, or raise Not_found. Chapter 16. The unix library: Unix system calls 173 val getpwuid : int -> passwd_entry Find an entry in passwd with the given user id, or raise Not_found. val getgrgid : int -> group_entry Find an entry in group with the given group id, or raise Not_found. Internet addresses type inet_addr The abstract type of Internet addresses. val inet_addr_of_string : string -> inet_addr val string_of_inet_addr : inet_addr -> string Conversions between string with the format XXX.YYY.ZZZ.TTT and Internet addresses. inet_addr_of_string raises Failure when given a string that does not match this format. val inet_addr_any : inet_addr A special Internet address, for use only with bind, representing all the Internet addresses that the host machine possesses. Sockets type socket_domain = PF_UNIX (* Unix domain *) | PF_INET (* Internet domain *) The type of socket domains. type socket_type = SOCK_STREAM (* Stream socket *) | SOCK_DGRAM (* Datagram socket *) | SOCK_RAW (* Raw socket *) | SOCK_SEQPACKET (* Sequenced packets socket *) The type of socket kinds, specifying the semantics of communications. type sockaddr = ADDR_UNIX of string | ADDR_INET of inet_addr * int The type of socket addresses. ADDR_UNIX name is a socket address in the Unix domain; name is a file name in the file system. ADDR_INET(addr,port) is a socket address in the Internet domain; addr is the Internet address of the machine, and port is the port number. val socket : socket_domain -> socket_type -> int -> file_descr Chapter 16. The unix library: Unix system calls 174 Create a new socket in the given domain, and with the given kind. The third argument is the protocol type; 0 selects the default protocol for that kind of sockets. val socketpair : socket_domain -> socket_type -> int -> file_descr * file_descr Create a pair of unnamed sockets, connected together. val accept : file_descr -> file_descr * sockaddr Accept connections on the given socket. The returned descriptor is a socket connected to the client; the returned address is the address of the connecting client. val bind : file_descr -> sockaddr -> unit Bind a socket to an address. val connect : file_descr -> sockaddr -> unit Connect a socket to an address. val listen : file_descr -> int -> unit Set up a socket for receiving connection requests. The integer argument is the maximal number of pending requests. type shutdown_command = SHUTDOWN_RECEIVE (* Close for receiving *) | SHUTDOWN_SEND (* Close for sending *) | SHUTDOWN_ALL (* Close both *) The type of commands for shutdown. val shutdown : file_descr -> shutdown_command -> unit Shutdown a socket connection. SHUTDOWN_SEND as second argument causes reads on the other end of the connection to return an end-of-file condition. SHUTDOWN_RECEIVE causes writes on the other end of the connection to return a closed pipe condition (SIGPIPE signal). val getsockname : file_descr -> sockaddr Return the address of the given socket. val getpeername : file_descr -> sockaddr Return the address of the host connected to the given socket. type msg_flag = MSG_OOB | MSG_DONTROUTE | MSG_PEEK The flags for recv, recvfrom, send and sendto. Chapter 16. The unix library: Unix system calls 175 val recv : file_descr -> string -> int -> int -> msg_flag list -> int val recvfrom : file_descr -> string -> int -> int -> msg_flag list -> int * sockaddr Receive data from an unconnected socket. val send : file_descr -> string -> int -> int -> msg_flag list -> int val sendto : file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int Send data over an unconnected socket. type socket_option = SO_DEBUG (* Record debugging information *) | SO_BROADCAST (* Permit sending of broadcast messages *) | SO_REUSEADDR (* Allow reuse of local addresses for bind *) | SO_KEEPALIVE (* Keep connection active *) | SO_DONTROUTE (* Bypass the standard routing algorithms *) | SO_OOBINLINE (* Leave out-of-band data in line *) The socket options settable with setsockopt. val getsockopt : file_descr -> socket_option -> bool Return the current status of an option in the given socket. val setsockopt : file_descr -> socket_option -> bool -> unit Set or clear an option in the given socket. High-level network connection functions val open_connection : sockaddr -> in_channel * out_channel Connect to a server at the given address. Return a pair of buffered channels connected to the server. Remember to call flush on the output channel at the right times to ensure correct synchronization. val shutdown_connection : in_channel -> unit ``Shut down'' a connection established with open_connection; that is, transmit an end-of-file condition to the server reading on the other side of the connection. val establish_server : (in_channel -> out_channel -> 'a) -> sockaddr -> unit Establish a server on the given address. The function given as first argument is called for each connection with two buffered channels connected to the client. A new process is created for each connection. The function establish_server never returns normally. Host and protocol databases type host_entry = Chapter 16. The unix library: Unix system calls 176 { h_name : string; h_aliases : string array; h_addrtype : socket_domain; h_addr_list : inet_addr array } Structure of entries in the hosts database. type protocol_entry = { p_name : string; p_aliases : string array; p_proto : int } Structure of entries in the protocols database. type service_entry = { s_name : string; s_aliases : string array; s_port : int; s_proto : string } Structure of entries in the services database. val gethostname : unit -> string Return the name of the local host. val gethostbyname : string -> host_entry Find an entry in hosts with the given name, or raise Not_found. val gethostbyaddr : inet_addr -> host_entry Find an entry in hosts with the given address, or raise Not_found. val getprotobyname : string -> protocol_entry Find an entry in protocols with the given name, or raise Not_found. val getprotobynumber : int -> protocol_entry Find an entry in protocols with the given protocol number, or raise Not_found. val getservbyname : string -> string -> service_entry Find an entry in services with the given name, or raise Not_found. val getservbyport : int -> string -> service_entry Find an entry in services with the given service number, or raise Not_found. Chapter 16. The unix library: Unix system calls 177 Terminal interface The following functions implement the POSIX standard terminal interface. They provide control over asynchronous communication ports and pseudo-terminals. Refer to the termios man page for a complete description. type terminal_io = { Input modes: mutable c_ignbrk: bool; (* Ignore the break condition. *) mutable c_brkint: bool; (* Signal interrupt on break condition. *) mutable c_ignpar: bool; (* Ignore characters with parity errors. *) mutable c_parmrk: bool; (* Mark parity errors. *) mutable c_inpck: bool; (* Enable parity check on input. *) mutable c_istrip: bool; (* Strip 8th bit on input characters. *) mutable c_inlcr: bool; (* Map NL to CR on input. *) mutable c_igncr: bool; (* Ignore CR on input. *) mutable c_icrnl: bool; (* Map CR to NL on input. *) mutable c_ixon: bool; (* Recognize XON/XOFF characters on input. *) mutable c_ixoff: bool; (* Emit XON/XOFF chars to control input flow. *) Output modes: mutable c_opost: bool; (* Enable output processing. *) Control modes: mutable c_obaud: int; (* Output baud rate (0 means close connection).*) mutable c_ibaud: int; (* Input baud rate. *) mutable c_csize: int; (* Number of bits per character (5-8). *) mutable c_cstopb: int; (* Number of stop bits (1-2). *) mutable c_cread: bool; (* Reception is enabled. *) mutable c_parenb: bool; (* Enable parity generation and detection. *) mutable c_parodd: bool; (* Specify odd parity instead of even. *) mutable c_hupcl: bool; (* Hang up on last close. *) mutable c_clocal: bool; (* Ignore modem status lines. *) Local modes: mutable c_isig: bool; (* Generate signal on INTR, QUIT, SUSP. *) mutable c_icanon: bool; (* Enable canonical processing (line buffering and editing) *) mutable c_noflsh: bool; (* Disable flush after INTR, QUIT, SUSP. *) mutable c_echo: bool; (* Echo input characters. *) mutable c_echoe: bool; (* Echo ERASE (to erase previous character). *) mutable c_echok: bool; (* Echo KILL (to erase the current line). *) mutable c_echonl: bool; (* Echo NL even if c_echo is not set. *) Control characters: mutable c_vintr: char; (* Interrupt character (usually ctrl-C). *) mutable c_vquit: char; (* Quit character (usually ctrl-\). *) mutable c_verase: char; (* Erase character (usually DEL or ctrl-H). *) mutable c_vkill: char; (* Kill line character (usually ctrl-U). *) mutable c_veof: char; (* End-of-file character (usually ctrl-D). *) mutable c_veol: char; (* Alternate end-of-line char. (usually none). *) Chapter 16. The unix library: Unix system calls 178 mutable c_vmin: int; (* Minimum number of characters to read before the read request is satisfied. *) mutable c_vtime: int; (* Maximum read wait (in 0.1s units). *) mutable c_vstart: char; (* Start character (usually ctrl-Q). *) mutable c_vstop: char (* Stop character (usually ctrl-S). *) } val tcgetattr: file_descr -> terminal_io Return the status of the terminal referred to by the given file descriptor. type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH val tcsetattr: file_descr -> setattr_when -> terminal_io -> unit Set the status of the terminal referred to by the given file descriptor. The second argument indicates when the status change takes place: immediately (TCSANOW), when all pending output has been transmitted (TCSADRAIN), or after flushing all input that has been received but not read (TCSAFLUSH). TCSADRAIN is recommended when changing the output parameters; TCSAFLUSH, when changing the input parameters. val tcsendbreak: file_descr -> int -> unit Send a break condition on the given file descriptor. The second argument is the duration of the break, in 0.1s units; 0 means standard duration (0.25s). val tcdrain: file_descr -> unit Waits until all output written on the given file descriptor has been transmitted. type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH val tcflush: file_descr -> flush_queue -> unit Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: TCIFLUSH flushes data received but not read, TCOFLUSH flushes data written but not transmitted, and TCIOFLUSH flushes both. type flow_action = TCOOFF | TCOON | TCIOFF | TCION val tcflow: file_descr -> flow_action -> unit Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: TCOOFF suspends output, TCOON restarts output, TCIOFF transmits a STOP character to suspend input, and TCION transmits a START character to restart input. Windows: Below is a list of the functions that are not implemented, or only partially implemented, under Windows. Functions not mentioned are fully implemented and behave as described previously in this chapter. Chapter 16. The unix library: Unix system calls 179 --------------------------------------------------------------------- |Functions |Comment | --------------------------------------------------------------------- |fork |not implemented, use create_process | | |or threads | |wait |not implemented, use waitpid | |waitpid |can only wait for a given PID, not | | |any child process | |getppid |not implemented (meaningless under | | |Windows) | |nice |not implemented | |truncate, ftruncate |not implemented | |lstat, fstat |not implemented | |link, symlink, readlink |not implemented (no links under | | |Windows) | |chmod, fchmod |not implemented | |chown, fchown |not implemented (make no sense on a | | |DOS file system) | |umask |not implemented | |set_nonblock, clear_nonblock |implemented as dummy functions; use | | |threads instead of non-blocking I/O | |rewinddir |not implemented; re-open the direc- | | |tory instead | |mkfifo |not implemented | |ioctl_int, ioctl_ptr |not implemented (no ioctl in | | |Windows) | |select |not implemented; use threads instead | |lockf |not implemented | |kill, pause |not implemented (no inter-process | | |signals in Windows) | |gettimeofday, alarm, times |not implemented | |getitimer, setitimer |not implemented | |getuid, getgid |always return 1 | |getgid, getegid, getgroups |not implemented | |setuid, setgid |not implemented | |getpwnam, getpwuid |always raise Not_found | |getgrnam, getgrgid |always raise Not_found | |type socket_domain |the domain PF_UNIX is not supported; | | |PF_INET is fully supported | |establish_server |not implemented; use threads | |terminal functions (tc*) |not implemented | --------------------------------------------------------------------- Chapter 17 The num library: arbitrary-precision rational arithmetic The num library implements exact-precision rational arithmetic. It is built upon the state-of-the-art BigNum arbitrary-precision integer arithmetic package, and therefore achieves very high performance. The functions provided in this library are fully documented in The CAML Numbers Reference Manual by Valerie Menissier-Morain, technical report 141, INRIA, july 1992 (available by anonymous FTP from ftp.inria.fr, directory INRIA/publications/RT, file RT-0141.ps.Z). A summary of the functions is given below. Unix: Programs that use the num library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options nums.cma other files -cclib -lnums ocamlopt other options nums.cmxa other files -cclib -lnums For interactive use of the nums library, do: ocamlmktop -custom -o mytop nums.cma -cclib -lnums ./mytop Windows: Programs that use the num library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options nums.cma other files %CAMLLIB%/libnums.lib ocamlopt other options nums.cmxa other files %CAMLLIB%/libnums.lib For interactive use of the nums library, do: ocamlmktop -custom -o mytop.exe nums.cma %CAMLLIB%/libnums.lib ./mytop.exe 180 Chapter 17. The num library: arbitrary-precision rational arithmetic 181 17.1 Module Num: operation on arbitrary-precision numbers open Nat open Big_int open Ratio Numbers (type num) are arbitrary-precision rational numbers, plus the special elements 1/0 (infinity) and 0/0 (undefined). type num = Int of int | Big_int of big_int | Ratio of ratio The type of numbers. Arithmetic operations val (+/) : num -> num -> num val add_num : num -> num -> num Addition val minus_num : num -> num Unary negation. val (-/) : num -> num -> num val sub_num : num -> num -> num Subtraction val (*/) : num -> num -> num val mult_num : num -> num -> num Multiplication val square_num : num -> num Squaring val (//) : num -> num -> num val div_num : num -> num -> num Division val quo_num : num -> num -> num val mod_num : num -> num -> num Euclidean division: quotient and remainder val (**/) : num -> num -> num val power_num : num -> num -> num Exponentiation val is_integer_num : num -> bool Test if a number is an integer Chapter 17. The num library: arbitrary-precision rational arithmetic 182 val integer_num : num -> num val floor_num : num -> num val round_num : num -> num val ceiling_num : num -> num Approximate a number by an integer. floor_num n returns the largest integer smaller or equal to n. ceiling_num n returns the smallest integer bigger or equal to n. integer_num n returns the integer closest to n. In case of ties, rounds towards zero. round_num n returns the integer closest to n. In case of ties, rounds off zero. val sign_num : num -> int Return -1, 0 or 1 according to the sign of the argument. val (=/) : num -> num -> bool val ( num -> bool val (>/) : num -> num -> bool val (<=/) : num -> num -> bool val (>=/) : num -> num -> bool val (<>/) : num -> num -> bool val eq_num : num -> num -> bool val lt_num : num -> num -> bool val le_num : num -> num -> bool val gt_num : num -> num -> bool val ge_num : num -> num -> bool Usual comparisons between numbers val compare_num : num -> num -> int Return -1, 0 or 1 if the first argument is less than, equal to, or greater than the second argument. val max_num : num -> num -> num val min_num : num -> num -> num Return the greater (resp. the smaller) of the two arguments. val abs_num : num -> num Absolute value. val succ_num: num -> num succ n is n+1 val pred_num: num -> num pred n is n-1 val incr_num: num ref -> unit incr r is r:=!r+1, where r is a reference to a number. val decr_num: num ref -> unit decr r is r:=!r-1, where r is a reference to a number. Chapter 17. The num library: arbitrary-precision rational arithmetic 183 Coercions with strings val string_of_num : num -> string Convert a number to a string, using fractional notation. val approx_num_fix : int -> num -> string val approx_num_exp : int -> num -> string Approximate a number by a decimal. The first argument is the required precision. The second argument is the number to approximate. approx_fix uses decimal notation; the first argument is the number of digits after the decimal point. approx_exp uses scientific (exponential) notation; the first argument is the number of digits in the mantissa. val num_of_string : string -> num Convert a string to a number. Coercions between numerical types val int_of_num : num -> int val num_of_int : int -> num val nat_of_num : num -> nat val num_of_nat : nat -> num val num_of_big_int : big_int -> num val big_int_of_num : num -> big_int val ratio_of_num : num -> ratio val num_of_ratio : ratio -> num val float_of_num : num -> float 17.2 Module Arith_status: flags that control rational arithmetic val arith_status: unit -> unit Print the current status of the arithmetic flags. val get_error_when_null_denominator : unit -> bool val set_error_when_null_denominator : bool -> unit Get or set the flag null_denominator. When on, attempting to create a rational with a null denominator raises an exception. When off, rationals with null denominators are accepted. Initially: on. val get_normalize_ratio : unit -> bool val set_normalize_ratio : bool -> unit Get or set the flag normalize_ratio. When on, rational numbers are normalized after each operation. When off, rational numbers are not normalized until printed. Initially: off. val get_normalize_ratio_when_printing : unit -> bool val set_normalize_ratio_when_printing : bool -> unit Get or set the flag normalize_ratio_when_printing. When on, rational numbers are normalized before being printed. When off, rational numbers Chapter 17. The num library: arbitrary-precision rational arithmetic 184 are printed as is, without normalization. Initially: on. val get_approx_printing : unit -> bool val set_approx_printing : bool -> unit Get or set the flag approx_printing. When on, rational numbers are printed as a decimal approximation. When off, rational numbers are printed as a fraction. Initially: off. val get_floating_precision : unit -> int val set_floating_precision : int -> unit Get or set the parameter floating_precision. This parameter is the number of digits displayed when approx_printing is on. Initially: 12. Chapter 18 The str library: regular expressions and string processing The str library provides high-level string processing functions, some based on regular expressions. It is intended to support the kind of file processing that is usually performed with scripting languages such as awk, perl or sed. Unix: Programs that use the str library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options str.cma other files -cclib -lstr ocamlopt other options str.cmxa other files -cclib -lstr For interactive use of the str library, do: ocamlmktop -custom -o mytop str.cma -cclib -lstr ./mytop Windows: Programs that use the str library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options str.cma other files %CAMLLIB%/libstr.lib ocamlopt other options str.cmxa other files %CAMLLIB%/libstr.lib For interactive use of the str library, do: ocamlmktop -custom -o mytop.exe str.cma %CAMLLIB%/libstr.lib ./mytop.exe 18.1 Module Str: regular expressions and high-level string processing Regular expressions type regexp 185 Chapter 18. The str library: regular expressions and string processing 186 The type of compiled regular expressions. val regexp: string -> regexp Compile a regular expression. The syntax for regular expressions is the same as in Gnu Emacs. The special characters are $^.*+?[]\. The following constructs are recognized: . matches any character except newline * (postfix) matches the previous expression zero, one or several times + (postfix) matches the previous expression one or several times ? (postfix) matches the previous expression once or not at all [..] character set; ranges are denoted with -, as in a-z; an initial ^, as in ^0-9, complements the set ^ matches at beginning of line $ matches at end of line \| (infix) alternative between two expressions \(..\) grouping and naming of the enclosed expression \1 the text matched by the first \(...\) expression (\2 for the second expression, etc) \b matches word boundaries \ quotes special characters. val regexp_case_fold: string -> regexp Same as regexp, but the compiled expression will match text in a case-insensitive way: uppercase and lowercase letters will be considered equivalent. String matching and searching val string_match: regexp -> string -> int -> bool string_match r s start tests whether the characters in s starting at position start match the regular expression r. The first character of a string has position 0, as usual. val search_forward: regexp -> string -> int -> int search_forward r s start searchs the string s for a substring matching the regular expression r. The search starts at position start and proceeds towards the end of the string. Return the position of the first character of the matched substring, or raise Not_found if no substring matches. val search_backward: regexp -> string -> int -> int Same as search_forward, but the search proceeds towards the beginning of the string. val matched_string: string -> string matched_string s returns the substring of s that was matched by the latest string_match, search_forward or search_backward. The user must make sure that the parameter s is the same string that was passed to the matching or searching function. Chapter 18. The str library: regular expressions and string processing 187 val match_beginning: unit -> int val match_end: unit -> int match_beginning() returns the position of the first character of the substring that was matched by string_match, search_forward or search_backward. match_end() returns the position of the character following the last character of the matched substring. val matched_group: int -> string -> string matched_group n s returns the substring of s that was matched by the nth group \(...\) of the regular expression during the latest string_match, search_forward or search_backward. The user must make sure that the parameter s is the same string that was passed to the matching or searching function. val group_beginning: int -> int val group_end: int -> int group_beginning n returns the position of the first character of the substring that was matched by the nth group of the regular expression. group_end n returns the position of the character following the last character of the matched substring. Replacement val global_replace: regexp -> string -> string -> string global_replace regexp repl s returns a string identical to s, except that all substrings of s that match regexp have been replaced by repl. The replacement text repl can contain \1, \2, etc; these sequences will be replaced by the text matched by the corresponding group in the regular expression. \0 stands for the text matched by the whole regular expression. val replace_first: regexp -> string -> string -> string Same as global_replace, except that only the first substring matching the regular expression is replaced. val global_substitute: regexp -> (string -> string) -> string -> string global_substitute regexp subst s returns a string identical to s, except that all substrings of s that match regexp have been replaced by the result of function subst. The function subst is called once for each matching substring, and receives s (the whole text) as argument. val substitute_first: regexp -> (string -> string) -> string -> string Same as global_substitute, except that only the first substring matching the regular expression is replaced. Splitting val split: regexp -> string -> string list Chapter 18. The str library: regular expressions and string processing 188 split r s splits s into substrings, taking as delimiters the substrings that match r, and returns the list of substrings. For instance, split (regexp "[ \t]+") s splits s into blank-separated words. val bounded_split: regexp -> string -> int -> string list Same as split, but splits into at most n substrings, where n is the extra integer parameter. Extracting substrings val string_before: string -> int -> string string_before s n returns the substring of all characters of s that precede position n (excluding the character at position n). val string_after: string -> int -> string string_after s n returns the substring of all characters of s that follow position n (including the character at position n). val first_chars: string -> int -> string first_chars s n returns the first n characters of s. This is the same function as string_before. val last_chars: string -> int -> string last_chars s n returns the last n characters of s. Chapter 19 The threads library The threads library allows concurrent programming in Objective Caml. It provides multiple threads of control (also called lightweight processes) that execute concurrently in the same memory space. Threads communicate by in-place modification of shared data structures, or by sending and receiving data on communication channels. The threads library is implemented by time-sharing on a single processor. It will not take advantage of multi-processor machines. Using this library will therefore never make programs run faster. However, many programs are easier to write when structured as several communicating processes. This library cannot be used in native-code programs compiled with ocamlopt; it can only be used with bytecode programs compiled with ocamlc. Unix: Programs that use the threads library must be linked as follows: ocamlc -thread -custom other options threads.cma other files - cclib -lthreads All object files on the command line must also have been compiled with the -thread option, which selects a special, thread-safe version of the standard library (see chapter 6). Windows: Programs that use the threads library must be linked as follows: ocamlc -thread -custom other options threads.cma other files \ %CAMLLIB%/libthreads.lib All object files on the command line must also have been compiled with the -thread option, which selects a special, thread-safe version of the standard library (see chapter 6). Interactive use through a toplevel built with ocamlmktop is impractical, because the Objective Caml toplevel itself is not thread-aware. 19.1 Module Thread: user-level lightweight threads type t 189 Chapter 19. The threads library 190 The type of thread handles. Thread creation and termination val create : ('a -> 'b) -> 'a -> t Thread.create funct arg creates a new thread of control, in which the function application funct arg is executed concurrently with the other threads of the program. The application of Thread.create returns the handle of the newly created thread. The new thread terminates when the application funct arg returns, either normally or by raising an uncaught exception. In the latter case, the exception is printed on standard error, but not propagated back to the parent thread. Similarly, the result of the application funct arg is discarded and not directly accessible to the parent thread. val self : unit -> t Return the thread currently executing. val id : t -> int Return the identifier of the given thread. A thread identifier is an integer that identifies uniquely the thread. It can be used to build data structures indexed by threads. val exit : unit -> unit Terminate prematurely the currently executing thread. val kill : t -> unit Terminate prematurely the thread whose handle is given. Suspending threads val delay: float -> unit delay d suspends the execution of the calling thread for d seconds. The other program threads continue to run during this time. val join : t -> unit join th suspends the execution of the calling thread until the thread th has terminated. val wait_read : Unix.file_descr -> unit val wait_write : Unix.file_descr -> unit Suspend the execution of the calling thread until at least one character is available for reading (wait_read) or one character can be written without blocking (wait_write) on the given Unix file descriptor. val wait_timed_read : Unix.file_descr -> float -> bool val wait_timed_write : Unix.file_descr -> float -> bool Chapter 19. The threads library 191 Same as wait_read and wait_write, but wait for at most the amount of time given as second argument (in seconds). Return true if the file descriptor is ready for input/output and false if the timeout expired. val wait_pid : int -> int * Unix.process_status wait_pid p suspends the execution of the calling thread until the Unix process specified by the process identifier p terminates. A pid p of -1 means wait for any child. A pid of 0 means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. Returns the pid of the child caught and its termination status, as per Unix.wait. 19.2 Module Mutex: locks for mutual exclusion Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if m is the mutex associated with the data structure D): Mutex.lock m; (* Critical section that operates over D *); Mutex.unlock m type t The type of mutexes. val create: unit -> t Return a new mutex. val lock: t -> unit Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex. val try_lock: t -> bool Same as try_lock, but does not suspend the calling thread if the mutex is already locked: just return false immediately in that case. If the mutex is unlocked, lock it and return true. val unlock: t -> unit Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. 19.3 Module Condition: condition variables to synchronize between threads Condition variables are used when one thread wants to wait until another thread has finished doing something: the former thread ``waits'' on the Chapter 19. The threads library 192 condition variable, the latter thread ``signals'' the condition when it is done. Condition variables should always be protected by a mutex. The typical use is (if D is a shared data structure, m its mutex, and c is a condition variable): Mutex.lock m; while (* some predicate P over D is not satisfied *) do Condition.wait c m done; (* Modify D *) if (* the predicate P over D is now satified *) then Condi- tion.signal c; Mutex.unlock m type t The type of condition variables. val create: unit -> t Return a new condition variable. val wait: t -> Mutex.t -> unit wait c m atomically unlocks the mutex m and suspends the calling process on the condition variable c. The process will restart after the condition variable c has been signalled. The mutex m is locked again before wait returns. val signal: t -> unit signal c restarts one of the processes waiting on the condition variable c. val broadcast: t -> unit broadcast c restarts all processes waiting on the condition variable c. 19.4 Module Event: first-class synchronous communication This module implements synchronous interprocess communications over channels. As in John Reppy's Concurrent ML system, the communication events are first-class values: they can be built and combined independently before being offered for communication. type 'a channel The type of communication channels carrying values of type 'a. val new_channel: unit -> 'a channel Return a new channel. Chapter 19. The threads library 193 type 'a event The type of communication events returning a result of type 'a. val send: 'a channel -> 'a -> unit event send ch v returns the event consisting in sending the value v over the channel ch. The result value of this event is (). val receive: 'a channel -> 'a event receive ch returns the event consisting in receiving a value from the channel ch. The result value of this event is the value received. val choose: 'a event list -> 'a event choose evl returns the event that is the alternative of all the events in the list evl. val wrap: 'a event -> ('a -> 'b) -> 'b event wrap ev fn returns the event that performs the same communications as ev, then applies the post-processing function fn on the return value. val guard: (unit -> 'a event) -> 'a event guard fn returns the event that, when synchronized, computes fn() and behaves as the resulting event. This allows to compute events with side-effects at the time of the synchronization operation. val sync: 'a event -> 'a ``Synchronize'' on an event: offer all the communication possibilities specified in the event to the outside world, and block until one of the communications succeed. The result value of that communication is returned. val select: 'a event list -> 'a ``Synchronize'' on an alternative of events. select evl is shorthand for sync(choose evl). val poll: 'a event -> 'a option Non-blocking version of sync: offer all the communication possibilities specified in the event to the outside world, and if one can take place immediately, perform it and return Some r where r is the result value of that communication. Otherwise, return None without blocking. 19.5 Module ThreadUnix: thread-compatible system calls This module reimplements some of the functions from Unix so that they only block the calling thread, not all threads in the program, if they cannot complete immediately. See the documentation of the Unix module for more precise descriptions of the functions below. Chapter 19. The threads library 194 Process handling val execv : string -> string array -> unit val execve : string -> string array -> string array -> unit val execvp : string -> string array -> unit val wait : unit -> int * Unix.process_status val waitpid : Unix.wait_flag list -> int -> int * Unix.process_status val system : string -> Unix.process_status Basic input/output val read : Unix.file_descr -> string -> int -> int -> int val write : Unix.file_descr -> string -> int -> int -> int Input/output with timeout val timed_read : Unix.file_descr -> string -> int -> int -> float -> int val timed_write : Unix.file_descr -> string -> int -> int -> float -> int Behave as read and write, except that Unix_error(ETIMEDOUT,_,_) is raised if no data is available for reading or ready for writing after d seconds. The delay d is given in the fifth argument, in seconds. Interfacing with the standard input/output library val in_channel_of_descr : Unix.file_descr -> in_channel val out_channel_of_descr : Unix.file_descr -> out_channel Pipes and redirections val pipe : unit -> Unix.file_descr * Unix.file_descr val open_process_out: string -> out_channel val open_process: string -> in_channel * out_channel Time val sleep : int -> unit Sockets val socket : Unix.socket_domain -> Unix.socket_type -> int -> Unix.file_descr val socketpair : Unix.socket_domain -> Unix.socket_type -> int -> Unix.file_descr * Unix.file_descr val accept : Unix.file_descr -> Unix.file_descr * Unix.sockaddr val connect : Unix.file_descr -> Unix.sockaddr -> unit val recv : Unix.file_descr -> string -> int -> int -> Unix.msg_flag list - > int val recvfrom : Unix.file_descr -> string -> int -> int -> Unix.msg_flag list -> int * Unix.sockaddr val send : Unix.file_descr -> string -> int -> int -> Unix.msg_flag list -> int val sendto : Unix.file_descr -> string -> int -> int -> Unix.msg_flag list -> Unix.sockaddr -> int val open_connection : Unix.sockaddr -> in_channel * out_channel Chapter 19. The threads library 195 val establish_server : (in_channel -> out_channel -> 'a) -> Unix.sockaddr -> unit Chapter 20 The graphics library The graphics library provides a set of portable drawing primitives. Drawing takes place in a separate window that is created when open_graph is called. This library cannot be used in native-code programs compiled with ocamlopt (because it uses signals, which are not supported by the native-code compiler); it can only be used with bytecode programs compiled with ocamlc. Unix: This library is implemented under the X11 windows system. Programs that use the graphics library must be linked as follows: ocamlc -custom other options graphics.cma other files \ -cclib -lgraphics -cclib -lX11 For interactive use of the graphics library, do: ocamlmktop -custom -o mytop graphics.cma -cclib -lgraphics - cclib -lX11 ./mytop Windows: This library is available only under the toplevel application ocamlwin.exe. Before using it, the Caml part of this library must be loaded in-core, either by typing #load graphics.cmo;; in the input windows or by using the ``Load'' entry of the ``File'' menu. The screen coordinates are interpreted as shown in the figure below. Notice that the coordinate system used is the same as in mathematics: y increases from the bottom of the screen to the top of the screen, and angles are measured counterclockwise (in degrees). Drawing is clipped to the screen. 196 Chapter 20. The graphics library 197 y | ------------------------- size_y() | | | Screen | | | | | | |pixel at (x,y) | y --------- | | | | | | | | | | | | | | ------------------------------ | | | x | x size_x() Here are the graphics mode specifications supported by open_graph on the X11 implementation of this library: the argument to open_graph has the format "display-name geometry", where display-name is the name of the X-windows display to connect to, and geometry is a standard X-windows geometry specification. The two components are separated by a space. Either can be omitted, or both. Examples: open_graph "foo:0" connects to the display foo:0 and creates a window with the default geometry open_graph "foo:0 300x100+50-0" connects to the display foo:0 and creates a window 300 pixels wide by 100 pixels tall, at location (50,0) open_graph " 300x100+50-0" connects to the default display and creates a window 300 pixels wide by 100 pixels tall, at location (50,0) open_graph "" connects to the default display and creates a window with the default geometry. 20.1 Module Graphics: machine-independent graphics primitives exception Graphic_failure of string Raised by the functions below when they encounter an error. Initializations val open_graph: string -> unit Show the graphics window or switch the screen to graphic mode. The graphics window is cleared. The string argument is used to pass optional information on the desired graphics mode, the graphics window size, and so on. Its interpretation is implementation-dependent. If the empty string is given, a sensible default is selected. val close_graph: unit -> unit Delete the graphics window or switch the screen back to text mode. Chapter 20. The graphics library 198 val clear_graph : unit -> unit Erase the graphics window. val size_x : unit -> int val size_y : unit -> int Return the size of the graphics window. Coordinates of the screen pixels range over 0 .. size_x()-1 and 0 .. size_y()-1. Drawings outside of this rectangle are clipped, without causing an error. The origin (0,0) is at the lower left corner. Colors type color = int A color is specified by its R, G, B components. Each component is in the range 0..255. The three components are packed in an int: 0xRRGGBB, where RR are the two hexadecimal digits for the red component, GG for the green component, BB for the blue component. val rgb: int -> int -> int -> color rgb r g b returns the integer encoding the color with red component r, green component g, and blue component b. r, g and b are in the range 0..255. val set_color : color -> unit Set the current drawing color. val black : color val white : color val red : color val green : color val blue : color val yellow : color val cyan : color val magenta : color Some predefined colors. val background: color val foreground: color Default background and foreground colors (usually, either black foreground on a white background or white foreground on a black background). clear_graph fills the screen with the background color. The initial drawing color is foreground. Point and line drawing val plot : int -> int -> unit Plot the given point with the current drawing color. Chapter 20. The graphics library 199 val point_color : int -> int -> color Return the color of the given point. val moveto : int -> int -> unit Position the current point. val current_point : unit -> int * int Return the position of the current point. val lineto : int -> int -> unit Draw a line with endpoints the current point and the given point, and move the current point to the given point. val draw_arc : int -> int -> int -> int -> int -> int -> unit = "gr_draw_arc" "gr_draw_arc_nat" draw_arc x y rx ry a1 a2 draws an elliptical arc with center x,y, horizontal radius rx, vertical radius ry, from angle a1 to angle a2 (in degrees). The current point is unchanged. val draw_ellipse : int -> int -> int -> int -> unit draw_ellipse x y rx ry draws an ellipse with center x,y, horizontal radius rx and vertical radius ry. The current point is unchanged. val draw_circle : int -> int -> int -> unit draw_circle x y r draws a circle with center x,y and radius r. The current point is unchanged. val set_line_width : int -> unit Set the width of points and lines drawn with the functions above. Under X Windows, set_line_width 0 selects a width of 1 pixel and a faster, but less precise drawing algorithm than the one used when set_line_width 1 is specified. Text drawing val draw_char : char -> unit val draw_string : string -> unit Draw a character or a character string with lower left corner at current position. After drawing, the current position is set to the lower right corner of the text drawn. val set_font : string -> unit val set_text_size : int -> unit Set the font and character size used for drawing text. The interpretation of the arguments to set_font and set_text_size is implementation-dependent. Chapter 20. The graphics library 200 val text_size : string -> int * int Return the dimensions of the given text, if it were drawn with the current font and size. Filling val fill_rect : int -> int -> int -> int -> unit fill_rect x y w h fills the rectangle with lower left corner at x,y, width w and heigth h, with the current color. val fill_poly : (int * int) array -> unit Fill the given polygon with the current color. The array contains the coordinates of the vertices of the polygon. val fill_arc : int -> int -> int -> int -> int -> int -> unit = "gr_fill_arc" "gr_fill_arc_nat" Fill an elliptical pie slice with the current color. The parameters are the same as for draw_arc. val fill_ellipse : int -> int -> int -> int -> unit Fill an ellipse with the current color. The parameters are the same as for draw_ellipse. val fill_circle : int -> int -> int -> unit Fill a circle with the current color. The parameters are the same as for draw_circle. Images type image The abstract type for images, in internal representation. Externally, images are represented as matrices of colors. val transp : color In matrices of colors, this color represent a ``transparent'' point: when drawing the corresponding image, all pixels on the screen corresponding to a transparent pixel in the image will not be modified, while other points will be set to the color of the corresponding point in the image. This allows superimposing an image over an existing background. val make_image : color array array -> image Convert the given color matrix to an image. Each sub-array represents one horizontal line. All sub-arrays must have the same length; otherwise, exception Graphic_failure is raised. Chapter 20. The graphics library 201 val dump_image : image -> color array array Convert an image to a color matrix. val draw_image : image -> int -> int -> unit Draw the given image with lower left corner at the given point. val get_image : int -> int -> int -> int -> image Capture the contents of a rectangle on the screen as an image. The parameters are the same as for fill_rect. val create_image : int -> int -> image create_image w h returns a new image w pixels wide and h pixels tall, to be used in conjunction with blit_image. The initial image contents are random. val blit_image : image -> int -> int -> unit blit_image img x y copies screen pixels into the image img, modifying img in-place. The pixels copied are those inside the rectangle with lower left corner at x,y, and width and height equal to those of the image. Mouse and keyboard events type status = { mouse_x : int; (* X coordinate of the mouse *) mouse_y : int; (* Y coordinate of the mouse *) button : bool; (* true if a mouse button is pressed *) keypressed : bool; (* true if a key has been pressed *) key : char } (* the character for the key pressed *) To report events. type event = Button_down (* A mouse button is pressed *) | Button_up (* A mouse button is released *) | Key_pressed (* A key is pressed *) | Mouse_motion (* The mouse is moved *) | Poll (* Don't wait; return immediately *) To specify events to wait for. val wait_next_event : event list -> status Wait until one of the events specified in the given event list occurs, and return the status of the mouse and keyboard at that time. If Poll is given in the event list, return immediately with the current status. If the mouse cursor is outside of the graphics window, the mouse_x and mouse_y fields of the event are outside the range 0..size_x()-1, 0..size_y()-1. Keypresses are queued, and dequeued one by one when the Key_pressed event is specified. Chapter 20. The graphics library 202 Mouse and keyboard polling val mouse_pos : unit -> int * int Return the position of the mouse cursor, relative to the graphics window. If the mouse cursor is outside of the graphics window, mouse_pos() returns a point outside of the range 0..size_x()-1, 0..size_y()-1. val button_down : unit -> bool Return true if the mouse button is pressed, false otherwise. val read_key : unit -> char Wait for a key to be pressed, and return the corresponding character. Keypresses are queued. val key_pressed : unit -> bool Return true if a keypress is available; that is, if read_key would not block. Sound val sound : int -> int -> unit sound freq dur plays a sound at frequency freq (in hertz) for a duration dur (in milliseconds). Chapter 21 The dbm library: access to NDBM databases The dbm library provides access to NDBM databases under Unix. NDBM databases maintain key/data associations, where both the key and the data are arbitrary strings. They support fairly large databases (several gigabytes) and can retrieve a keyed item in one or two file system accesses. Refer to the Unix manual pages for more information. Unix: Programs that use the dbm library must be linked in ``custom runtime'' mode, as follows: ocamlc -custom other options dbm.cma other files -cclib -lmldbm - cclib -lndbm ocamlopt other options dbm.cmxa other files -cclib -lmldbm - cclib -lndbm For interactive use of the dbm library, do: ocamlmktop -custom -o mytop dbm.cma -cclib -lmldbm -cclib -lndbm ./mytop Depending on the Unix system used, the -cclib -lndbm option is not always necessary, or the library may have another name than -lndbm. Windows: This library is not available. 21.1 Module Dbm: interface to the NDBM databases type t The type of file descriptors opened on NDBM databases. type open_flag = Dbm_rdonly | Dbm_wronly | Dbm_rdwr | Dbm_create Flags for opening a database (see opendbm). exception Dbm_error of string 203 Chapter 21. The dbm library: access to NDBM databases 204 Raised by the following functions when an error is encountered. val opendbm : string -> open_flag list -> int -> t Open a descriptor on an NDBM database. The first argument is the name of the database (without the .dir and .pag suffixes). The second argument is a list of flags: Dbm_rdonly opens the database for reading only, Dbm_wronly for writing only, Dbm_rdwr for reading and writing; Dbm_create causes the database to be created if it does not already exist. The third argument is the permissions to give to the database files, if the database is created. val close : t -> unit Close the given descriptor. val find : t -> string -> string find db key returns the data associated with the given key in the database opened for the descriptor db. Raise Not_found if the key has no associated data. val add : t -> string -> string -> unit add db key data inserts the pair (key, data) in the database db. If the database already contains data associated with key, raise Dbm_error "Entry already exists". val replace : t -> string -> string -> unit replace db key data inserts the pair (key, data) in the database db. If the database already contains data associated with key, that data is discarded and silently replaced by the new data. val remove : t -> string -> unit remove db key data removes the data associated with key in db. If key has no associated data, raise Dbm_error "dbm_delete". val firstkey : t -> string val nextkey : t -> string Enumerate all keys in the given database, in an unspecified order. firstkey db returns the first key, and repeated calls to nextkey db return the remaining keys. Not_found is raised when all keys have been enumerated. val iter : (string -> string -> 'a) -> t -> unit iter f db applies f to each (key, data) pair in the database db. f receives key as first argument and data as second argument. Part V Appendix 205 Index to the library ! (operator), 126 alarm, 171 != (operator), 117 append, 130 & (operator), 117 approx_num_exp, 183 && (operator), 117 approx_num_fix, 183 * (operator), 118 Arg (module), 129 ** (operator), 119 argv, 156 **/ (operator), 181 arith_status, 183 *. (operator), 119 Arith_status (module), 183 */ (operator), 181 Array (module), 130 + (operator), 118 asin, 120 +. (operator), 119 asr (operator), 119 +/ (operator), 181 assoc, 146 - (operator), 118 assq, 146 -. (operator), 119 at_exit, 127 -/ (operator), 181 atan, 120 / (operator), 118 atan2, 120 /. (operator), 119 background, 198 // (operator), 181 Bad (exception), 130 := (operator), 126 basename, 133 < (operator), 117 big_int_of_num, 183 (operator), 116 blit_image, 201 <>/ (operator), 182 blue, 198 = (operator), 116 bounded_split, 188 =/ (operator), 182 Break (exception), 158 == (operator), 117 broadcast, 192 > (operator), 117 button_down, 202 >/ (operator), 182 >= (operator), 117 catch, 148 >=/ (operator), 182 catch_break, 158 @ (operator), 121 ceiling_num, 182 ^ (operator), 120 channel, 132 || (operator), 117 Char (module), 131 ~- (operator), 118 chdir, 157, 167 ~-. (operator), 119 check_suffix, 133 abs, 118 chmod, 166 abs_float, 120 choose, 193 abs_num, 182 chop_extension, 133 accept, 174, 195 chop_suffix, 133 access, 166 chown, 166 acos, 120 chr, 131 add, 142, 150, 204 clear, 142, 150, 153 add_num, 181 clear_close_on_exec, 167 206 Index to the library 207 clear_graph, 198 environment, 161 clear_nonblock, 166 eprintf, 149 clear_parser, 148 eq_num, 182 close, 164, 204 error_message, 161 close_box, 134 escaped, 132, 156 close_graph, 197 establish_server, 175, 195 close_in, 126 Event (module), 192 close_out, 124 execv, 162, 194 close_process, 168 execve, 162, 194 close_process_in, 168 execvp, 162, 194 close_process_out, 168 execvpe, 162 close_tbox, 136 exists, 145 closedir, 167 exists2, 145 code, 131 exit, 127, 190 combine, 146 Exit (exception), 116 command, 157 exp, 120 compare, 117 Failure (exception), 115 compare_num, 182 failwith, 116 concat, 130, 132, 156 fchmod, 166 Condition (module), 191 fchown, 166 connect, 174, 195 file, 132 copy, 131, 148, 155 file_exists, 156 cos, 120 Filename (module), 132 count, 155 fill, 131, 156 create, 130, 141, 150, 153, 155, fill_arc, 200 190--192 fill_circle, 200 create_image, 201 fill_ellipse, 200 create_matrix, 130 fill_poly, 200 create_process, 168 fill_rect, 200 create_process_env, 168 find, 142, 204 current_dir_name, 132 find_all, 142 current_point, 199 first_chars, 188 cyan, 198 firstkey, 204 Dbm (module), 203 flatten, 144 Dbm_error (exception), 203 float, 120, 151 decr, 126 float_of_num, 183 decr_num, 182 float_of_string, 120 delay, 190 floor_num, 182 descr_of_in_channel, 164 flush, 123 descr_of_out_channel, 164 fold_left, 145 Digest (module), 132 fold_left2, 145 dirname, 133 fold_right, 145 div_num, 181 fold_right2, 145 Division_by_zero (exception), 116 for_all, 145 draw_arc, 199 for_all2, 145 draw_char, 199 force_newline, 135 draw_circle, 199 foreground, 198 draw_ellipse, 199 fork, 162 draw_image, 201 Format (module), 133 draw_string, 199 fprintf, 149 dump_image, 201 from, 154 dup, 166 from_channel, 143 dup2, 166 from_function, 143 from_string, 143 empty, 155 fst, 121 Empty (exception), 150, 153 fstat, 165 End_of_file (exception), 116 ftruncate, 164 Index to the library 208 full_init, 150 Hashtbl (module), 141 full_major, 140 hd, 144 Gc (module), 139 id, 190 ge_num, 182 in_channel_length, 126 Genlex (module), 140 in_channel_of_descr, 164, 194 get, 130, 140, 155 incr, 126 get_approx_printing, 184 incr_num, 182 get_ellipsis_text, 137 inet_addr_any, 173 get_error_when_null_denominator, 183 inet_addr_of_string, 173 get_floating_precision, 184 init, 150 get_formatter_output_functions, 137 input, 125, 132 get_image, 201 input_binary_int, 125 get_margin, 136 input_byte, 125 get_max_boxes, 137 input_char, 125 get_max_indent, 137 input_line, 125 get_normalize_ratio, 183 input_value, 125 get_normalize_ratio_when_printing, 183 int, 151 getcwd, 157, 167 int_of_num, 183 getegid, 172 int_of_string, 120 getenv, 156 integer_num, 182 geteuid, 172 interactive, 157 getgid, 172 invalid_arg, 116 getgrgid, 173 Invalid_argument (exception), 115 getgrnam, 172 ioctl_int, 169 getgroups, 172 ioctl_ptr, 169 gethostbyaddr, 176 is_absolute, 133 gethostbyname, 176 is_integer_num, 181 gethostname, 176 iter, 131, 142, 144, 150, 153, 154, getitimer, 171 204 getlogin, 172 iter2, 145 getpeername, 174 join, 190 getpid, 163 junk, 155 getppid, 163 getprotobyname, 176 key_pressed, 202 getprotobynumber, 176 kill, 170, 190 getpwnam, 172 getpwuid, 173 land (operator), 118 getservbyname, 176 last_chars, 188 getservbyport, 176 le_num, 182 getsockname, 174 length, 130, 144, 150, 153, 155 getsockopt, 175 lexeme, 143 gettimeofday, 170 lexeme_char, 144 getuid, 171 lexeme_end, 144 global_replace, 187 lexeme_start, 144 global_substitute, 187 Lexing (module), 143 gmtime, 170 lineto, 199 Graphic_failure (exception), 197 link, 165 Graphics (module), 197 list, 153 green, 198 List (module), 144 group_beginning, 187 listen, 174 group_end, 187 lnot, 119 gt_num, 182 localtime, 170 guard, 193 lock, 191 handle_unix_error, 161 lockf, 169 hash, 142 log, 120 lor (operator), 118 hash_param, 142 lseek, 164 Index to the library 209 lsl (operator), 119 of_list, 131, 154 lsr (operator), 119 of_string, 154 lstat, 165 Oo (module), 148 lt_num, 182 open_box, 134 lxor (operator), 119 open_connection, 175, 195 magenta, 198 open_graph, 197 major, 140 open_hbox, 134 make, 155 open_hovbox, 134 Make (functor), 147, 152 open_hvbox, 134 make_formatter, 138 open_in, 124 make_image, 200 open_in_bin, 124 make_lexer, 141 open_in_gen, 125 map, 131, 145 open_out, 123 Map (module), 146 open_out_bin, 123 map2, 145 open_out_gen, 123 match_beginning, 187 open_process, 168, 194 match_end, 187 open_process_in, 168 Match_failure (exception), 49--51, 115 open_process_out, 168, 194 matched_group, 187 open_tbox, 136 matched_string, 186 open_vbox, 134 max, 117 opendbm, 204 max_int, 118 opendir, 167 max_num, 182 openfile, 163 mem, 146 or (operator), 117 mem_assoc, 146 OrderedType (module type), 146, 151 memq, 146 out_channel_length, 124 merge, 153 out_channel_of_descr, 164, 194 min, 117 Out_of_memory (exception), 116 min_int, 118 output, 123, 132 min_num, 182 output_binary_int, 124 minor, 140 output_byte, 124 minus_num, 181 output_char, 123 mkdir, 167 output_string, 123 mkfifo, 168 output_value, 124 mktime, 170 parse, 129 mod (operator), 118 Parse_error (exception), 148, 154 mod_num, 181 Parse_failure (exception), 154 mouse_pos, 202 Parsing (module), 148 moveto, 199 pause, 170 mult_num, 181 peek, 150, 155 Mutex (module), 191 Pervasives (module), 114 nat_of_num, 183 pipe, 167, 194 new_channel, 192 plot, 198 next, 154 point_color, 199 nextkey, 204 poll, 193 nice, 163 pop, 153 not, 117 pos_in, 126 Not_found (exception), 116 pos_out, 124 nth, 144 power_num, 181 Num (module), 181 pp_close_box, 138 num_of_big_int, 183 pp_close_tbox, 138 num_of_int, 183 pp_force_newline, 138 num_of_nat, 183 pp_get_ellipsis_text, 138 num_of_ratio, 183 pp_get_formatter_output_functions, 138 num_of_string, 183 pp_get_margin, 138 pp_get_max_boxes, 138 of_channel, 154 pp_get_max_indent, 138 Index to the library 210 pp_open_box, 138 quo_num, 181 pp_open_hbox, 138 raise, 115 pp_open_hovbox, 138 Random (module), 150 pp_open_hvbox, 138 ratio_of_num, 183 pp_open_tbox, 138 read, 164, 194 pp_open_vbox, 138 read_float, 122 pp_print_as, 138 read_int, 122 pp_print_bool, 138 read_key, 202 pp_print_break, 138 read_line, 122 pp_print_char, 138 readdir, 167 pp_print_cut, 138 readlink, 169 pp_print_float, 138 really_input, 125 pp_print_flush, 138 receive, 193 pp_print_if_newline, 138 recv, 175, 195 pp_print_int, 138 recvfrom, 175, 195 pp_print_newline, 138 red, 198 pp_print_space, 138 ref, 126 pp_print_string, 138 regexp, 186 pp_print_tab, 138 regexp_case_fold, 186 pp_print_tbreak, 138 remove, 142, 156, 204 pp_set_ellipsis_text, 138 rename, 156, 165 pp_set_formatter_out_channel, 138 replace, 204 pp_set_formatter_output_functions, 138 replace_first, 187 pp_set_margin, 138 rev, 144 pp_set_max_boxes, 138 rewinddir, 167 pp_set_max_indent, 138 rgb, 198 pp_set_tab, 138 rhs_end, 148 pred, 118 rhs_start, 148 pred_num, 182 rmdir, 167 prerr_char, 122 round_num, 182 prerr_endline, 122 prerr_float, 122 search_backward, 186 prerr_int, 122 search_forward, 186 prerr_newline, 122 seek_in, 126 prerr_string, 122 seek_out, 124 print, 148 select, 169, 193 print_as, 135 self, 190 print_bool, 135 send, 175, 193, 195 print_break, 135 sendto, 175, 195 print_char, 121, 135 set, 130, 140, 155 print_cut, 135 Set (module), 151 print_endline, 121 set_approx_printing, 184 print_float, 121, 135 set_close_on_exec, 167 print_flush, 135 set_color, 198 print_if_newline, 136 set_ellipsis_text, 137 print_int, 121, 135 set_error_when_null_denominator, 183 print_newline, 122, 136 set_floating_precision, 184 print_space, 135 set_font, 199 print_stat, 140 set_formatter_out_channel, 137 print_string, 121, 135 set_formatter_output_functions, 137 print_tab, 136 set_line_width, 199 print_tbreak, 136 set_margin, 136 Printexc (module), 148 set_max_boxes, 137 printf, 149 set_max_indent, 136 Printf (module), 149 set_nonblock, 166 push, 153 set_normalize_ratio, 183 Queue (module), 150 set_normalize_ratio_when_printing, 183 Index to the library 211 set_tab, 136 string_of_float, 120 set_text_size, 199 string_of_inet_addr, 173 setgid, 172 string_of_int, 120 setitimer, 171 string_of_num, 183 setsockopt, 175 sub, 130, 156 setuid, 172 sub_num, 181 shutdown, 174 substitute_first, 187 shutdown_connection, 175 substring, 132 sigabrt, 158 succ, 118 sigalrm, 158 succ_num, 182 sigchld, 158 symbol_end, 148 sigcont, 158 symbol_start, 148 sigfpe, 158 symlink, 168 sighup, 158 sync, 193 sigill, 158 Sys (module), 156 sigint, 158 Sys_error (exception), 116 sigkill, 158 system, 163, 194 sign_num, 182 take, 150 signal, 157, 192 sigpipe, 158 tan, 120 sigprof, 158 tcdrain, 178 sigquit, 158 tcflow, 178 sigsegv, 158 tcflush, 178 sigstop, 158 tcgetattr, 178 sigterm, 158 tcsendbreak, 178 sigtstp, 158 tcsetattr, 178 sigttin, 158 temp_file, 133 sigttou, 158 text_size, 200 sigusr1, 158 Thread (module), 189 sigusr2, 158 ThreadUnix (module), 193 sigvtalrm, 158 time, 170 sin, 120 timed_read, 194 size_x, 198 timed_write, 194 size_y, 198 times, 171 sleep, 171, 194 tl, 144 snd, 121 to_list, 131 socket, 173, 195 transp, 200 socketpair, 174, 195 truncate, 120, 164 Sort (module), 153 try_lock, 191 sound, 202 split, 146, 187 umask, 166 sprintf, 149 Unix (module), 160 sqrt, 120 Unix_error (exception), 161 square_num, 181 unlink, 165 Stack (module), 153 unlock, 191 stat, 140, 165 utimes, 171 std_formatter, 138 wait, 162, 192, 194 stderr, 121, 163 wait_next_event, 201 stdin, 121, 163 wait_pid, 191 stdout, 121, 163 wait_read, 190 Str (module), 185 wait_timed_read, 190 Stream (module), 154 wait_timed_write, 190 string, 132 wait_write, 190 String (module), 155 waitpid, 162, 194 string_after, 188 white, 198 string_before, 188 wrap, 193 string_match, 186 string_of_bool, 120 write, 164, 194 Index to the library 212 yellow, 198 Index of keywords and, see let, type, 57, 59 method, 57--59 as, 43--46, 57, 59 module, 59, 61, 62, 64 begin, 47, 48 mutable, 55--59 class, 57, 59, 61, 64 new, 47, 54 closed, 57, 59 not, 47 constraint, 57, 59 of, see type, exception do, see while, for open, 59, 61, 62, 64 done, see while, for or, 47, 51 downto, see for parser, 66 else, see if private, 57--59 end, 47, 48, 57, 59, 60, 62, 63 rec, see let exception, 56, 59, 61, 62, 64 sig, 59, 60 external, 59, 60, 62, 63 struct, 62, 63 false, 42 then, see if, 57, 59 for, 47, 51 to, see for fun, 47, 49 true, 42 function, 47, 49 try, 47, 52 functor, 59, 62, 64 type, 55, 59--64 if, 47, 50 val, 57--60 in, see let virtual, 57, 59 inherit, 57--59 let, 47, 49, 62, 63 when, 47, 49 while, 51 match, 47, 51, 66 with, see match, try, 59, 62 213