The Ocaml System Release 4.13: Documentation and User'S Manual
The Ocaml System Release 4.13: Documentation and User'S Manual
The Ocaml System Release 4.13: Documentation and User'S Manual
release 4.13
Documentation and user’s manual
Xavier Leroy,
Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy and Jérôme Vouillon
I An introduction to OCaml 11
3 Objects in OCaml 45
3.1 Classes and objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2 Immediate objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.3 Reference to self . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.4 Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5 Virtual methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.6 Private methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.7 Class interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.8 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.9 Multiple inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.10 Parameterized classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.11 Polymorphic methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.12 Using coercions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.13 Functional objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
1
2
4 Labeled arguments 77
4.1 Optional arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.2 Labels and type inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.3 Suggestions for labeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5 Polymorphic variants 83
5.1 Basic use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.2 Advanced use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.3 Weaknesses of polymorphic variants . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
30 The dynlink library: dynamic loading and linking of object files 847
30.1 Module Dynlink : Dynamic loading of .cmo, .cma and .cmxs files. . . . . . . . . . . 847
V Indexes 853
This manual documents the release 4.13 of the OCaml system. It is organized as follows.
• Part II, “The OCaml language”, is the reference description of the language.
• Part III, “The OCaml tools”, documents the compilers, toplevel system, and programming
utilities.
• Part IV, “The OCaml library”, describes the modules provided in the standard library.
• Part V, “Indexes”, contains an index of all identifiers defined in the standard library, and an
index of keywords.
Conventions
OCaml runs on several operating systems. The parts of this manual that are specific to one
operating system are presented as shown below:
Unix:
This is material specific to the Unix family of operating systems, including Linux and macOS.
Windows:
This is material specific to Microsoft Windows (Vista, 7, 8, 10).
License
The OCaml system is copyright © 1996–2021 Institut National de Recherche en Informatique et en
Automatique (INRIA). INRIA holds all ownership rights to the OCaml system.
The OCaml system is open source and can be freely redistributed. See the file LICENSE in the
distribution for licensing information.
The OCaml documentation and user’s manual is copyright © 2021 Institut National de
Recherche en Informatique et en Automatique (INRIA).
The OCaml documentation and user’s manual is licensed under a Creative Commons
Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0), https://creativecommons.
org/licenses/by-sa/4.0/.
9
10 Foreword
Availability
The complete OCaml distribution can be accessed via the website https://ocaml.org/. This site
contains a lot of additional information on OCaml.
Part I
An introduction to OCaml
11
Chapter 1
This part of the manual is a tutorial introduction to the OCaml language. A good familiarity with
programming in a conventional languages (say, C or Java) is assumed, but no prior exposure to
functional languages is required. The present chapter introduces the core language. Chapter 2
deals with the module system, chapter 3 with the object-oriented features, chapter 4 with labeled
arguments, chapter 5 with polymorphic variants, chapter 6 with the limitations of polymorphism,
and chapter 8 gives some advanced examples.
1.1 Basics
For this overview of OCaml, we use the interactive system, which is started by running ocaml from
the Unix shell or Windows command prompt. 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 OCaml 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
13
14
# 1.0 * 2;;
Error : This expression has type float but an expression was expected of type
int
Recursive functions are defined with the let rec binding:
# let rec fib n =
if n < 2 then n else fib (n - 1) + fib (n - 2);;
val fib : int -> int = <fun>
# fib 10;;
- : int = 55
• characters
# 'a';;
- : char = 'a'
# int_of_char '\n';;
- : int = 10
# {|This is a quoted string, here, neither \ nor " are special characters|};;
- : string =
"This is a quoted string, here, neither \\ nor \" are special characters"
# {|"\\"|}="\"\\\\\"";;
- : bool = true
Predefined data structures include tuples, arrays, and lists. There are also general mechanisms
for defining your own data structures, such as records and variants, which will be covered in more
detail 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 OCaml data structures, lists do not need to be explicitly allocated and deallocated
from memory: all memory management is entirely automatic in OCaml. Similarly, there is no
explicit handling of pointers: the OCaml compiler silently introduces pointers where necessary.
As with most OCaml data structures, inspecting and destructuring lists is performed by pattern-
matching. List patterns have exactly the same form as list expressions, with identifiers representing
unspecified parts of the list. As an example, here is insertion sort on a list:
# let rec sort lst =
match lst with
[] -> []
| head :: tail -> insert head (sort tail)
and insert elt lst =
match lst with
[] -> [elt]
| head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail
;;
val sort : 'a list -> 'a list = <fun>
val insert : 'a -> 'a list -> 'a list = <fun>
# sort l;;
- : string list = ["a"; "etc."; "is"; "tale"; "told"]
The type inferred for sort, 'a list -> 'a list, means that sort can actually apply to lists
of any type, and returns a list of the same type. The type 'a is a type variable, and stands for
any given type. The reason why sort can apply to lists of any type is that the comparisons (=,
<=, etc.) are polymorphic in OCaml: 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]
OCaml data structures are immutable, but a few (most notably arrays) are mutable, meaning that
they can be modified in-place at any time.
The OCaml notation for the type of a function with multiple arguments is
arg1_type -> arg2_type -> ... -> return_type. For example, the type inferred for insert,
'a -> 'a list -> 'a list, means that insert takes two arguments, an element of any type 'a
and a list with elements of the same type 'a and returns a list of the same type.
# sin' pi;;
- : float = -1.00000000013961143
Even function composition is definable:
# let compose f g = function x -> f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
# let add_ratio r1 r2 =
{num = r1.num * r2.denom + r2.num * r1.denom;
denom = r1.denom * r2.denom};;
val add_ratio : ratio -> ratio -> ratio = <fun>
# let translate p dx dy =
p.x <- p.x +. dx; p.y <- p.y +. dy;;
val translate : mutable_point -> float -> float -> unit = <fun>
# mypoint;;
- : mutable_point = {x = 1.; y = 2.}
OCaml 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, with
operators ! to fetch the current contents of the reference and := to assign the contents. Variables
can then be emulated by let-binding a reference. For instance, here is an in-place insertion sort
over arrays:
# let insertion_sort a =
for i = 1 to Array.length a - 1 do
let val_i = a.(i) in
let j = ref i in
while !j > 0 && val_i < a.(!j - 1) do
a.(!j) <- a.(!j - 1);
j := !j - 1
done;
a.(!j) <- val_i
done;;
val insertion_sort : 'a array -> unit = <fun>
References are also useful to write functions that maintain a current state between two calls to
the function. For instance, the following pseudo-random number generator keeps the last returned
number in a reference:
# let current_rand = ref 0;;
val current_rand : int ref = {contents = 0}
# let random () =
current_rand := !current_rand * 25713 + 1345;
!current_rand;;
val random : unit -> int = <fun>
Again, there is nothing magical with references: they are implemented as a single-field mutable
record, as follows.
# type 'a ref = { mutable contents: 'a };;
type 'a ref = { mutable contents : 'a; }
# let ( ! ) r = r.contents;;
val ( ! ) : 'a ref -> 'a = <fun>
In some special cases, you may need to store a polymorphic function in a data structure, keeping
its polymorphism. Doing this requires user-provided type annotations, since polymorphism is only
introduced automatically for global definitions. However, you can explicitly give polymorphic types
to record fields.
# type idref = { mutable id: 'a. 'a -> 'a };;
type idref = { mutable id : 'a. 'a -> 'a; }
# g r;;
called id
called id
- : int * bool = (1, true)
1.6 Exceptions
OCaml provides exceptions for signalling and handling exceptional conditions. Exceptions can also
be used as a general-purpose non-local control structure, although this should not be overused since
it can make the code harder to understand. Exceptions are declared with the exception construct,
and signalled with the raise operator. For instance, the function below for taking the head of a
list uses an exception to signal the case where an empty list is given.
# exception Empty_list;;
exception Empty_list
# let head l =
match l with
[] -> raise Empty_list
| hd :: tl -> hd;;
val head : 'a list -> 'a = <fun>
# head [];;
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 associ-
ated 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:
24
# name_of_binary_digit 0;;
- : string = "zero"
# name_of_binary_digit (-1);;
- : string = "not a binary digit"
The with part does pattern matching on the exception value with the same syntax and behavior
as match. Thus, several exceptions can be caught by one try. . . with construct:
# let rec first_named_value values names =
try
List.assoc (head values) names
with
| Empty_list -> "no named value"
| Not_found -> first_named_value (List.tl values) names;;
val first_named_value : 'a list -> ('a * string) list -> string = <fun>
Note that lazy_two has type int lazy_t. However, the type 'a lazy_t is an internal type
name, so the type 'a Lazy.t should be preferred when possible.
When we finally need the result of a lazy expression, we can call Lazy.force on that expression
to force its evaluation. The function force comes from standard-library module Lazy[25.26].
# Lazy.force lazy_two;;
lazy_two evaluation
- : int = 2
Notice that our function call above prints “lazy_two evaluation” and then returns the plain
value of the computation.
Now if we look at the value of lazy_two, we see that it is not displayed as <lazy> anymore but
as lazy 2.
# lazy_two;;
- : int lazy_t = lazy 2
This is because Lazy.force memoizes the result of the forced expression. In other words,
every subsequent call of Lazy.force on that expression returns the result of the first computation
without recomputing the lazy expression. Let us force lazy_two once again.
# Lazy.force lazy_two;;
- : int = 2
The expression is not evaluated this time; notice that “lazy_two evaluation” is not printed.
The result of the initial computation is simply returned.
Lazy patterns provide another way to force a lazy expression.
# let lazy_l = lazy ([1; 2] @ [3; 4]);;
val lazy_l : int list lazy_t = <lazy>
# 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
# eval [("x", 1.0); ("y", 3.14)] (Prod(Sum(Var "x", Const 2.0), Var "y"));;
- : float = 9.42
Now for a real symbolic processing, we define the derivative of an expression with respect to a
variable dv:
# let rec deriv exp dv =
match exp with
Const c -> Const 0.0
| Var v -> if v = dv then Const 1.0 else Const 0.0
| Sum(f, g) -> Sum(deriv f dv, deriv g dv)
| Diff(f, g) -> Diff(deriv f dv, deriv g dv)
| Prod(f, g) -> Sum(Prod(f, deriv g dv), Prod(deriv f dv, g))
| Quot(f, g) -> Quot(Diff(Prod(deriv f dv, g), Prod(f, deriv g dv)),
Prod(g, g))
;;
28
1.9 Pretty-printing
As shown in the examples above, the internal representation (also called abstract syntax) of expres-
sions quickly becomes hard to read and write as the expressions get larger. We need a printer and
a parser to go back and forth between the abstract syntax and the concrete syntax, which in the
case of expressions is the familiar algebraic notation (e.g. 2*x+1).
For the printing function, we take into account the usual precedence rules (i.e. * binds tighter
than +) to avoid printing unnecessary parentheses. To this end, we maintain the current operator
precedence and print parentheses around an operator only if its precedence is less than the current
precedence.
# let print_expr exp =
(∗ Local function definitions ∗)
let open_paren prec op_prec =
if prec > op_prec then print_string "(" in
let close_paren prec op_prec =
if prec > op_prec then print_string ")" in
let rec print prec exp = (∗ prec is the current precedence ∗)
match exp with
Const c -> print_float c
| Var v -> print_string v
| Sum(f, g) ->
open_paren prec 0;
print 0 f; print_string " + "; print 0 g;
close_paren prec 0
| Diff(f, g) ->
open_paren prec 0;
print 0 f; print_string " - "; print 1 g;
close_paren prec 0
| Prod(f, g) ->
open_paren prec 2;
print 2 f; print_string " * "; print 2 g;
close_paren prec 2
| Quot(f, g) ->
open_paren prec 2;
print 2 f; print_string " / "; print 3 g;
close_paren prec 2
in print 0 exp;;
Chapter 1. The core language 29
# Printf.fprintf stdout
"The current setting is %a. \nThere is only %a\n"
(pp_option pp_int) (Some 3)
(pp_option pp_int) None
;;
The current setting is Some(3).
There is only None
- : unit = ()
If the value of its argument its None, the printer returned by pp_option printer prints None otherwise
it uses the provided printer to print Some .
Here is how to rewrite the pretty-printer using fprintf:
# let pp_expr ppf expr =
let open_paren prec op_prec output =
if prec > op_prec then Printf.fprintf output "%s" "(" in
let close_paren prec op_prec output =
if prec > op_prec then Printf.fprintf output "%s" ")" in
let rec print prec ppf expr =
match expr with
| Const c -> Printf.fprintf ppf "%F" c
| Var v -> Printf.fprintf ppf "%s" v
| Sum(f, g) ->
open_paren prec 0 ppf;
Printf.fprintf ppf "%a + %a" (print 0) f (print 0) g;
close_paren prec 0 ppf
| Diff(f, g) ->
open_paren prec 0 ppf;
Printf.fprintf ppf "%a - %a" (print 0) f (print 1) g;
close_paren prec 0 ppf
| Prod(f, g) ->
open_paren prec 2 ppf;
Printf.fprintf ppf "%a * %a" (print 2) f (print 2) g;
close_paren prec 2 ppf
| Quot(f, g) ->
open_paren prec 2 ppf;
Printf.fprintf ppf "%a / %a" (print 2) f (print 3) g;
close_paren prec 2 ppf
in print 0 ppf expr;;
val pp_expr : out_channel -> expression -> unit = <fun>
Chapter 1. The core language 31
(* File gcd.ml *)
let rec gcd a b =
if b = 0 then a
else gcd b (a mod b);;
let main () =
let a = int_of_string Sys.argv.(1) in
let b = int_of_string Sys.argv.(2) in
Printf.printf "%d\n" (gcd a b);
exit 0;;
main ();;
3
$ ./gcd 7 11
1
More complex standalone OCaml programs are typically composed of multiple source files, and
can link with precompiled libraries. Chapters 11 and 14 explain how to use the batch compilers
ocamlc and ocamlopt. Recompilation of multi-file OCaml projects can be automated using third-
party build systems, such as dune.
Chapter 2
2.1 Structures
A primary motivation for modules is to package together related definitions (such as the definitions
of a data type and associated operations over that type) and enforce a consistent naming scheme for
these definitions. This avoids running out of names or accidentally confusing names. Such a package
is called a structure and is introduced by the 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)
33
34
# let x = 1 :: empty ;;
Error : This expression has type 'a PrioQueue . queue
but an expression was expected of type int list
A partial solution to this conundrum is to open modules locally, making the components of the
module available only in the concerned expression. This can also make the code both easier to
read (since the open statement is closer to where it is used) and easier to refactor (since the code
fragment is more self-contained). Two constructions are available for this purpose:
# let open PrioQueue in
insert empty 1 "hello";;
Chapter 2. The module system 35
# PrioQueue.[|empty|] = PrioQueue.([|empty|]);;
- : bool = true
let remove_top_opt x =
try Some(remove_top x) with Queue_is_empty -> None
let extract_opt x =
try Some(extract x) with Queue_is_empty -> None
end;;
module PrioQueueOpt :
sig
type priority = int
type 'a queue =
'a PrioQueue.queue =
Empty
36
2.2 Signatures
Signatures are interfaces for structures. A signature specifies which components of a structure
are accessible from the outside, and with which type. It can be used to hide some components
of a structure (e.g. local function definitions) or export some components with a restricted type.
For instance, the signature below specifies the three priority queue operations empty, insert and
extract, but not the auxiliary function remove_top. Similarly, it makes the queue type abstract
(by not providing its actual representation as a concrete type).
# module type PRIOQUEUE =
sig
type priority = int (∗ still concrete ∗)
type 'a queue (∗ now abstract ∗)
val empty : 'a queue
val insert : 'a queue -> int -> 'a -> 'a queue
val extract : 'a queue -> int * 'a * 'a queue
exception Queue_is_empty
end;;
module type PRIOQUEUE =
sig
type priority = int
type 'a queue
val empty : 'a queue
val insert : 'a queue -> int -> 'a -> 'a queue
val extract : 'a queue -> int * 'a * 'a queue
exception Queue_is_empty
end
Restricting the PrioQueue structure by this signature results in another view of the PrioQueue
structure where the remove_top function is not accessible and the actual representation of priority
queues is hidden:
# module AbstractPrioQueue = (PrioQueue : PRIOQUEUE);;
module AbstractPrioQueue : PRIOQUEUE
# AbstractPrioQueue.remove_top ;;
Error : Unbound value Abstr actPr ioQueu e . remove_top
Chapter 2. The module system 37
Like for modules, it is possible to include a signature to copy its components inside the current
signature. For instance, we can extend the PRIOQUEUE signature with the extract_opt function:
# module type PRIOQUEUE_WITH_OPT =
sig
include PRIOQUEUE
val extract_opt : 'a queue -> (int * 'a * 'a queue) option
end;;
module type PRIOQUEUE_WITH_OPT =
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
val extract_opt : 'a queue -> (int * 'a * 'a queue) option
end
2.3 Functors
Functors are “functions” from modules to modules. Functors let you create parameterized modules
and then provide other modules as parameter(s) to get a specific implementation. For instance,
a Set module implementing sets as sorted lists could be parameterized to work with any module
that provides an element type and a comparison function compare (such as OrderedString):
# type comparison = Less | Equal | Greater;;
type comparison = Less | Equal | Greater
# module Set =
functor (Elt: ORDERED_TYPE) ->
struct
type element = Elt.t
type set = element list
let empty = []
let rec add x s =
match s with
[] -> [x]
| hd::tl ->
match Elt.compare x hd with
Equal -> s (∗ x is already in s ∗)
| Less -> x :: s (∗ x is smaller than all elements of s ∗)
| Greater -> hd :: add x tl
let rec member x s =
match s with
[] -> false
| hd::tl ->
match Elt.compare x hd with
Equal -> true (∗ x belongs to s ∗)
| Less -> false (∗ x is smaller than all elements of s ∗)
| Greater -> member x tl
end;;
module Set :
functor (Elt : ORDERED_TYPE) ->
sig
type element = Elt.t
type set = element list
val empty : 'a list
val add : Elt.t -> Elt.t list -> Elt.t list
val member : Elt.t -> Elt.t list -> bool
end
By applying the Set functor to a structure implementing an ordered type, we obtain set operations
for this type:
# module OrderedString =
struct
type t = string
let compare x y = if x = y then Equal else if x < y then Less else Greater
end;;
module OrderedString :
sig type t = string val compare : 'a -> 'a -> comparison end
module AbstractSet2 :
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:
Abstracting a type component in a functor result is a powerful technique that provides a high
degree of type safety, as we now illustrate. Consider an ordering over character strings that is
different from the standard ordering implemented in the OrderedString structure. For instance,
we compare strings without distinguishing upper and lower case.
# module NoCaseString =
struct
type t = string
let compare s1 s2 =
OrderedString.compare (String.lowercase_ascii s1) (String.lowercase_ascii s2)
end;;
module NoCaseString :
sig type t = string val compare : string -> string -> comparison end
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.
• the interface file A.mli, which contains a sequence of specifications, analogous to the inside
of a sig. . . end construct.
These two files together define a structure named A as if the following definition was entered at
top-level:
module A: sig (* contents of file A.mli *) end
= struct (* contents of file A.ml *) end;;
The files that define the compilation units can be compiled separately using the ocamlc -c
command (the -c option means “compile only, do not try to link”); this produces compiled interface
files (with extension .cmi) and compiled object code files (with extension .cmo). When all units
have been compiled, their .cmo files are linked together using the ocamlc command. For instance,
the following commands compile and link a program composed of two compilation units Aux and
Main:
$ ocamlc -c Aux.mli # produces aux.cmi
$ ocamlc -c Aux.ml # produces aux.cmo
$ ocamlc -c Main.mli # produces main.cmi
$ ocamlc -c Main.ml # produces main.cmo
$ ocamlc -o theprogram Aux.cmo Main.cmo
The program behaves exactly as if the following phrases were entered at top-level:
module Aux: sig (* contents of Aux.mli *) end
= struct (* contents of Aux.ml *) end;;
module Main: sig (* contents of Main.mli *) end
= struct (* contents of Main.ml *) end;;
In particular, Main can refer to Aux: the definitions and declarations contained in Main.ml and
Main.mli can refer to definition in Aux.ml, using the Aux.ident notation, provided these definitions
are exported in Aux.mli.
Chapter 2. The module system 43
The order in which the .cmo files are given to ocamlc 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.
Note that only top-level structures can be mapped to separately-compiled files, but neither
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.
44
Chapter 3
Objects in OCaml
45
46
- : int = 0
# p#move 3;;
- : unit = ()
# p#get_x;;
- : int = 3
The evaluation of the body of a class only takes place at object creation time. Therefore, in
the following example, the instance variable x is initialized to different values for two different
objects.
# let x0 = ref 0;;
val x0 : int ref = {contents = 0}
# class point =
object
val mutable x = incr x0; !x0
method get_x = x
method move d = x <- x + d
end;;
class point :
object val mutable x : int method get_x : int method move : int -> unit end
# new point#get_x;;
- : int = 1
# new point#get_x;;
- : int = 2
The class point can also be abstracted over the initial values of the x coordinate.
# class point = fun x_init ->
object
val mutable x = x_init
method get_x = x
method move d = x <- x + d
end;;
class point :
int ->
object val mutable x : int method get_x : int method move : int -> unit end
Like in function definitions, the definition above can be abbreviated as:
# class point x_init =
object
val mutable x = x_init
method get_x = x
method move d = x <- x + d
end;;
Chapter 3. Objects in OCaml 47
class point :
int ->
object val mutable x : int method get_x : int method move : int -> unit end
An instance of the class point is now a function that expects an initial parameter to create a point
object:
# new point;;
- : int -> point = <fun>
# p#get_x;;
- : int = 0
# p#move 3;;
- : unit = ()
# p#get_x;;
- : int = 3
Unlike classes, which cannot be defined inside an expression, immediate objects can appear
anywhere, using variables from their environment.
Chapter 3. Objects in OCaml 49
# let minmax x y =
if x < y then object method min = x method max = y end
else object method min = y method max = x end;;
val minmax : 'a -> 'a -> < max : 'a; min : 'a > = <fun>
Immediate objects have two weaknesses compared to classes: their types are not abbreviated,
and you cannot inherit from them. But these two weaknesses can be advantages in some situations,
as we will see in sections 3.3 and 3.10.
# p#print;;
7- : unit = ()
Dynamically, the variable s is bound at the invocation of a method. In particular, when the class
printable_point is inherited, the variable s will be correctly bound to the object of the subclass.
A common problem with self is that, as its type may be extended in subclasses, you cannot fix
it in advance. Here is a simple example.
# let ints = ref [];;
val ints : '_weak1 list ref = {contents = []}
# class my_int =
object (self)
method n = 1
50
3.4 Initializers
Let-bindings within class definitions are evaluated before the object is constructed. It is also possible
to evaluate an expression immediately after the object has been built. Such code is written as an
anonymous hidden method called an initializer. Therefore, it can access self and the instance
variables.
# class printable_point x_init =
let origin = (x_init / 10) * 10 in
object (self)
val mutable x = origin
method get_x = x
method move d = x <- x + d
method print = print_int self#get_x
initializer print_string "new point at "; self#print; print_newline ()
end;;
class printable_point :
int ->
object
val mutable x : int
method get_x : int
method move : int -> unit
method print : unit
end
Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Ini-
tializers are particularly useful to enforce invariants. Another example can be seen in section 8.1.
# p#move 10 ;;
Error : This expression has type restricted_point
It has no method move
# p#bump;;
- : unit = ()
Note that this is not the same thing as private and protected methods in Java or C++, which can
be called from other objects of the same class. This is a direct consequence of the independence
Chapter 3. Objects in OCaml 53
between types and classes in OCaml: two unrelated classes may produce objects of the same type,
and there is no way at the type level to ensure that an object comes from a specific class. However
a possible encoding of friend methods is given in section 3.17.
Private methods are inherited (they are by default visible in subclasses), unless they are hidden
by signature matching, as described below.
Private methods can be made public in a subclass.
# class point_again x =
object (self)
inherit restricted_point x
method virtual move : _
end;;
class point_again :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
The annotation virtual here is only used to mention a method without providing its definition.
Since we didn’t add the private annotation, this makes the method public, keeping the original
definition.
An alternative definition is
# class point_again x =
object (self : < move : _; ..> )
inherit restricted_point x
end;;
class point_again :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
The constraint on self’s type is requiring a public move method, and this is sufficient to override
private.
One could think that a private method should remain private in a subclass. However, since the
method is visible in a subclass, it is always possible to pick its code and define a method of the
same name that runs that code, so yet another (heavier) solution would be:
# class point_again x =
object
inherit restricted_point x as super
method move = super#move
end;;
54
class point_again :
int ->
object
val mutable x : int
method bump : unit
method get_x : int
method move : int -> unit
end
Of course, private methods can also be virtual. Then, the keywords must appear in this order
method private virtual.
3.8 Inheritance
We illustrate inheritance by defining a class of colored points that inherits from the class of points.
This class has all instance variables and all methods of class point, plus a new instance variable c
and a new method color.
# class colored_point x (c : string) =
object
inherit point x
val c = c
method color = c
end;;
class colored_point :
int ->
string ->
object
val c : string
val mutable x : int
method color : string
method get_offset : int
method get_x : int
method move : int -> unit
end
# p'#get_x, p'#color;;
- : int * string = (5, "red")
A point and a colored point have incompatible types, since a point has no method color. However,
the function get_x below is a generic function applying method get_x to any object p that has
this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it
applies to both points and colored points.
# let get_succ_x p = p#get_x + 1;;
val get_succ_x : < get_x : int; .. > -> int = <fun>
56
# p'#print;;
Chapter 3. Objects in OCaml 57
object
val mutable x : 'a
method get : 'a
method set : 'a -> unit
end
The method get has type 'a where 'a is unbound
The reason is that at least one of the methods has a polymorphic type (here, the type of the value
stored in the reference cell), thus either the class should be parametric, or the method type should
be constrained to a monomorphic type. A monomorphic instance of the class could be defined
by:
# class oref (x_init:int) =
object
val mutable x = x_init
method get = x
method set y = x <- y
end;;
class oref :
int ->
object val mutable x : int method get : int method set : int -> unit end
Note that since immediate objects do not define a class type, they have no such restriction.
# let new_oref x_init =
object
val mutable x = x_init
method get = x
method set y = x <- y
end;;
val new_oref : 'a -> < get : 'a; set : 'a -> unit > = <fun>
On the other hand, a class for polymorphic references must explicitly list the type parameters in
its declaration. Class type parameters are listed between [ and ]. The type parameters must also
be bound somewhere in the class body by a type constraint.
# class ['a] oref x_init =
object
val mutable x = (x_init : 'a)
method get = x
method set y = x <- y
end;;
class ['a] oref :
'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
# l;;
- : int intlist = <obj>
to be incompatible with the polymorphic type we gave (automatic instantiation only works for
toplevel types variables, not for inner quantifiers, where it becomes an undecidable problem.) So
the compiler cannot choose between those two types, and must be helped.
However, the type can be completely omitted in the class definition if it is already known,
through inheritance or type constraints on self. Here is an example of method overriding.
# class intlist_rev l =
object
inherit intlist l
method! fold f accu = List.fold_left f accu (List.rev l)
end;;
The following idiom separates description and definition.
# class type ['a] iterator =
object method fold : ('b -> 'a -> 'b) -> 'b -> 'b end;;
# class intlist' l =
object (self : int #iterator)
method empty = (l = [])
method fold f accu = List.fold_left f accu l
end;;
Note here the (self : int #iterator) idiom, which ensures that this object implements the
interface iterator.
Polymorphic methods are called in exactly the same way as normal methods, but you should
be aware of some limitations of type inference. Namely, a polymorphic method can only be called
if its type is known at the call site. Otherwise, the method will be assumed to be monomorphic,
and given an incompatible type.
# let sum lst = lst#fold (fun x y -> x+y) 0;;
val sum : < fold : (int -> int -> int) -> int -> 'a; .. > -> 'a = <fun>
# sum l ;;
Error : This expression has type intlist
but an expression was expected of type
< fold : ( int -> int -> int ) -> int -> 'a ; .. >
Types for method fold are incompatible
The workaround is easy: you should put a type constraint on the parameter.
# let sum (lst : _ #iterator) = lst#fold (fun x y -> x+y) 0;;
val sum : int #iterator -> int = <fun>
Of course the constraint may also be an explicit method type. Only occurrences of quantified
variables are required.
# let sum lst =
(lst : < fold : 'a. ('a -> _ -> 'a) -> 'a -> 'a; .. >)#fold (+) 0;;
val sum : < fold : 'a. ('a -> int -> 'a) -> 'a -> 'a; .. > -> int = <fun>
Chapter 3. Objects in OCaml 63
Another use of polymorphic methods is to allow some form of implicit subtyping in method
arguments. We have already seen in section 3.8 how some functions may be polymorphic in the
class of their argument. This can be extended to methods.
# class type point0 = object method get_x : int end;;
class type point0 = object method get_x : int end
# class distance_point x =
object
inherit point x
method distance : 'a. (#point0 as 'a) -> int =
fun other -> abs (other#get_x - x)
end;;
class distance_point :
int ->
object
val mutable x : int
method distance : #point0 -> int
method get_offset : int
method get_x : int
method move : int -> unit
end
The object type c0 is an abbreviation for <m : 'a; n : int> as 'a. Consider now the type
declaration:
# class type c1 = object method m : c1 end;;
class type c1 = object method m : c1 end
The object type c1 is an abbreviation for the type <m : 'a> as 'a. The coercion from an object
of type c0 to an object of type c1 is correct:
# fun (x:c0) -> (x : c0 :> c1);;
- : c0 -> c1 = <fun>
However, the domain of the coercion cannot always be omitted. In that case, the solution is to use
the explicit form. Sometimes, a change in the class-type definition can also solve the problem
# class type c2 = object ('a) method m : 'a end;;
class type c2 = object ('a) method m : 'a end
As a consequence, if the coercion is applied to self, as in the following example, the type of self is
unified with the closed type c (a closed object type is an object type without ellipsis). This would
constrain the type of self be closed and is thus rejected. Indeed, the type of self cannot be closed:
this would prevent any further extension of the class. Therefore, a type error is generated when
the unification of this type with another type would result in a closed object type.
# class c = object method m = 1 end
and d = object (self)
inherit c
method n = 2
method as_c = (self :> c)
end;;
Error : This expression cannot be coerced to type c = < m : int >; it has type
< as_c : c ; m : int ; n : int ; .. >
but is here used with type c
Self type cannot escape its class
However, the most common instance of this problem, coercing self to its current class, is detected
as a special case by the type checker, and properly typed.
# class c = object (self) method m = (self :> c) end;;
class c : object method m : c end
This allows the following idiom, keeping a list of all objects belonging to a class or its subclasses:
# let all_c = ref [];;
val all_c : '_weak3 list ref = {contents = []}
# class c (m : int) =
object (self)
method m = m
initializer all_c := (self :> c) :: !all_c
end;;
class c : int -> object method m : int end
This idiom can in turn be used to retrieve an object whose type has been weakened:
# let rec lookup_obj obj = function [] -> raise Not_found
| obj' :: l ->
if (obj :> < >) = (obj' :> < >) then obj' else lookup_obj obj l ;;
val lookup_obj : < .. > -> (< .. > as 'a) list -> 'a = <fun>
# p#get_x;;
- : int = 7
# (p#move 3)#get_x;;
- : int = 10
# (p#move_to 15)#get_x;;
- : int = 15
# p#get_x;;
- : int = 7
As with records, the form {< x >} is an elided version of {< x = x >} which avoids the repetition
of the instance variable name. Note that the type abbreviation functional_point is recursive,
which can be seen in the class type of functional_point: the type of self is 'a and 'a appears
inside the type of the method move.
The above definition of functional_point is not equivalent to the following:
# class bad_functional_point y =
object
val x = y
method get_x = x
method move d = new bad_functional_point (x+d)
method move_to x = new bad_functional_point x
end;;
class bad_functional_point :
int ->
object
val x : int
method get_x : int
method move : int -> bad_functional_point
method move_to : int -> bad_functional_point
end
While objects of either class will behave the same, objects of their subclasses will be different. In a
subclass of bad_functional_point, the method move will keep returning an object of the parent
class. On the contrary, in a subclass of functional_point, the method move will return an object
of the subclass.
Functional update is often used in conjunction with binary methods as illustrated in sec-
tion 8.2.1.
Chapter 3. Objects in OCaml 69
# p = q, p = p;;
- : bool * bool = (false, true)
Other generic comparisons such as (<, <=, ...) can also be used on objects. The relation < defines an
unspecified but strict ordering on objects. The ordering relationship between two objects is fixed
once for all after the two objects have been created and it is not affected by mutation of fields.
Cloning and override have a non empty intersection. They are interchangeable when used within
an object and without overriding any field:
# class copy =
object
method copy = {< >}
end;;
class copy : object ('a) method copy : 'a end
70
# class copy =
object (self)
method copy = Oo.copy self
end;;
class copy : object ('a) method copy : 'a end
Only the override can be used to actually override fields, and only the Oo.copy primitive can be
used externally.
Cloning can also be used to provide facilities for saving and restoring the state of objects.
# class backup =
object (self : 'mytype)
val mutable copy = None
method save = copy <- Some {< copy = None >}
method restore = match copy with Some x -> x | None -> self
end;;
class backup :
object ('a)
val mutable copy : 'a option
method restore : 'a
method save : unit
end
The above definition will only backup one level. The backup facility can be added to any class by
using multiple inheritance.
# class ['a] backup_ref x = object inherit ['a] oref x inherit backup end;;
class ['a] backup_ref :
'a ->
object ('b)
val mutable copy : 'b option
val mutable x : 'a
method get : 'a
method restore : 'b
method save : unit
method set : 'a -> unit
end
# class ['a] backup_ref x = object inherit ['a] oref x inherit backup end;;
class ['a] backup_ref :
'a ->
object ('b)
val mutable copy : 'b option
val mutable x : 'a
method clear : unit
method get : 'a
method restore : 'b
method save : unit
method set : 'a -> unit
end
# class money2 x =
object
inherit money x
method times k = {< repr = k *. repr >}
end;;
class money2 :
float ->
object ('a)
val repr : float
method leq : 'a -> bool
method times : float -> 'a
method value : float
end
It is however possible to define functions that manipulate objects of type either money or money2:
the function min will return the minimum of any two objects whose type unifies with #comparable.
The type of min is not the same as #comparable -> #comparable -> #comparable, as the ab-
breviation #comparable hides a type variable (an ellipsis). Each occurrence of this abbreviation
generates a new variable.
# let min (x : #comparable) y =
if x#leq y then x else y;;
val min : (#comparable as 'a) -> 'a -> 'a = <fun>
This function can be applied to objects of type money or money2.
# (min (new money 1.3) (new money 3.1))#value;;
- : float = 1.3
object ('a)
val repr : float
method leq : 'a -> bool
method plus : 'a -> 'a
method print : unit
method times : float -> 'a
method value : float
end
3.17 Friends
The above class money reveals a problem that often occurs with binary methods. In order to interact
with other objects of the same class, the representation of money objects must be revealed, using a
method such as value. If we remove all binary methods (here plus and leq), the representation
can easily be hidden inside objects by removing the method value as well. However, this is not
possible as soon as some binary method requires access to the representation of objects of the same
class (other than self).
# class safe_money x =
object (self : 'a)
val repr = x
method print = print_float repr
method times k = {< repr = k *. x >}
end;;
class safe_money :
float ->
object ('a)
val repr : float
method print : unit
method times : float -> 'a
end
Here, the representation of the object is known only to a particular object. To make it available to
other objects of the same class, we are forced to make it available to the whole world. However we
can easily restrict the visibility of the representation using the module system.
# module type MONEY =
sig
type t
class c : float ->
object ('a)
val repr : t
method value : t
method print : unit
method times : float -> 'a
method leq : 'a -> bool
method plus : 'a -> 'a
end
Chapter 3. Objects in OCaml 75
end;;
# module Euro : MONEY =
struct
type t = float
class c x =
object (self : 'a)
val repr = x
method value = repr
method print = print_float repr
method times k = {< repr = k *. x >}
method leq (p : 'a) = repr <= p#value
method plus (p : 'a) = {< repr = x +. p#value >}
end
end;;
Another example of friend functions may be found in section 8.2.4. These examples occur when
a group of objects (here objects of the same class) and functions should see each others internal
representation, while their representation should be hidden from the outside. The solution is always
to define all friends in the same module, give access to the representation and use a signature
constraint to make the representation abstract outside the module.
76
Chapter 4
Labeled arguments
# StringLabels.sub;;
- : string -> pos:int -> len:int -> string = <fun>
Such annotations of the form name: are called labels. They are meant to document the code,
allow more checking, and give more flexibility to function application. You can give such names to
arguments in your programs, by prefixing them with a tilde ~.
# let f ~x ~y = x - y;;
val f : x:int -> y:int -> int = <fun>
# f ~x:3 ~y:2;;
- : int = 1
Labels obey the same rules as other identifiers in OCaml, that is you cannot use a reserved
keyword (like in or to) as label.
Formal parameters and arguments are matched according to their respective labels, the absence
of label being interpreted as the empty label. This allows commuting arguments in applications.
One can also partially apply a function on any argument, creating a new function of the remaining
parameters.
# let f ~x ~y = x - y;;
77
78
# f ~y:2 ~x:3;;
- : int = 1
# ListLabels.fold_left;;
- : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun>
# ListLabels.fold_left ~init:0;;
- : f:(int -> 'a -> int) -> 'a list -> int = <fun>
If several arguments of a function bear the same label (or no label), they will not commute
among themselves, and order matters. But they can still commute with other arguments.
# let hline ~x:x1 ~x:x2 ~y = (x1, x2, y);;
val hline : x:'a -> x:'b -> y:'c -> 'a * 'b * 'c = <fun>
# bump 2;;
- : int = 3
# test ();;
- : ?z:int -> unit -> int * int * int = <fun>
# test2 ?x:None;;
- : ?y:int -> unit -> int * int * int = <fun>
val h' : (y:int -> x:int -> 'a) -> 'a = <fun>
# h' f ;;
Error : This expression has type x : int -> y : int -> int
but an expression was expected of type y : int -> x : int -> 'a
# bump_it bump 1 ;;
Error : This expression has type ? step : int -> int -> int
but an expression was expected of type step : int -> 'a -> 'b
The first case is simple: g is passed ~y and then ~x, but f expects ~x and then ~y. This is correctly
handled if we know the type of g to be x:int -> y:int -> int in advance, but otherwise this
causes the above type clash. The simplest workaround is to apply formal parameters in a standard
order.
The second example is more subtle: while we intended the argument bump to be of type
?step:int -> int -> int, it is inferred as step:int -> int -> 'a. These two types being
incompatible (internally normal and optional arguments are different), a type error occurs when
applying bump_it to the real bump.
We will not try here to explain in detail how type inference works. One must just understand
that there is not enough information in the above program to deduce the correct type of g or bump.
That is, there is no way to know whether an argument is optional or not, or which is the correct
order, by looking only at how a function is applied. The strategy used by the compiler is to assume
that there are no optional arguments, and that applications are done in the right order.
The right way to solve this problem for optional parameters is to add a type annotation to the
argument bump.
# let bump_it (bump : ?step:int -> int -> int) x =
bump ~step:2 x;;
val bump_it : (?step:int -> int -> int) -> int -> int = <fun>
• is easy to remember,
ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list
UnixLabels.write : file_descr -> buf:bytes -> pos:int -> len:int -> unit
When there are several objects of same nature and role, they are all left unlabeled.
ListLabels.iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
BytesLabels.blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
This principle also applies to functions of several arguments whose return type is a type variable,
as long as the role of each argument is not ambiguous. Labeling such functions may lead to
awkward error messages when one attempts to omit labels in an application, as we have seen with
ListLabels.fold_left.
Here are some of the label names you will find throughout the libraries.
82
Label Meaning
f: a function to be applied
pos: a position in a string, array or byte sequence
len: a length
buf: a byte sequence or string used as buffer
src: the source of an operation
dst: the destination of an operation
init: the initial value for an iterator
cmp: a comparison function, e.g. Stdlib.compare
mode: an operation mode or a flag list
All these are only suggestions, but keep in mind that the choice of labels is essential for read-
ability. Bizarre choices will make the program harder to maintain.
In the ideal, the right function name with right labels should be enough to understand the
function’s meaning. Since one can get this information with OCamlBrowser or the ocaml toplevel,
the documentation is only used when a more detailed specification is needed.
Chapter 5
Polymorphic variants
# `Number 1;;
- : [> `Number of int ] = `Number 1
83
84
contain an implicit type variable. Because each of the variant types appears only once in the whole
type, their implicit type variables are not shown.
The above variant types were polymorphic, allowing further refinement. When writing type an-
notations, one will most often describe fixed variant types, that is types that cannot be refined. This
is also the case for type abbreviations. Such types do not contain < or >, but just an enumeration
of the tags and their associated types, just like in a normal datatype definition.
# type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];;
type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
# f `E;;
- : [> `A | `B | `C | `D | `E ] = `E
Here we are seeing two phenomena. First, since this matching is open (the last case catches any
tag), we obtain the type [> `A | `B] rather than [< `A | `B] in a closed matching. Then, since
x is returned as is, input and return types are identical. The notation as 'a denotes such type
sharing. If we apply f to yet another tag `E, it gets added to the list.
# let f1 = function `A x -> x = 1 | `B -> true | `C -> false
let f2 = function `A x -> x = "a" | `B -> true ;;
val f1 : [< `A of int | `B | `C ] -> bool = <fun>
val f2 : [< `A of string | `B ] -> bool = <fun>
# type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];;
type 'a wlist = [ `Cons of 'a * 'a wlist | `Nil | `Snoc of 'a wlist * 'a ]
val f : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>
or combined with with aliases.
# let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";;
val g1 : [< `Tag1 of 'a | `Tag2 of 'b ] -> string = <fun>
# let g = function
| #myvariant as x -> g1 x
| `Tag3 -> "Tag3";;
val g : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>
# let f = function
| `As -> "A"
| #abc -> "other" ;;
val f : [< `A | `As | `B | `C ] -> string = <fun>
This chapter covers more advanced questions related to the limitations of polymorphic functions and
types. There are some situations in OCaml where the type inferred by the type checker may be less
generic than expected. Such non-genericity can stem either from interactions between side-effect
and typing or the difficulties of implicit polymorphic recursion and higher-rank polymorphism.
This chapter details each of these situations and, if it is possible, how to recover genericity.
# another_store := Some 0;
another_store ;;
- : int option ref = {contents = Some 0}
After storing an int inside another_store, the type of another_store has been updated from
'_weak2 option ref to int option ref. This distinction between weakly and generic polymor-
phic type variable protects OCaml programs from unsoundness and runtime errors. To understand
87
88
from where unsoundness might come, consider this simple function which swaps a value x with the
value stored inside a store reference, if there is such value:
# let swap store x = match !store with
| None -> store := Some x; x
| Some y -> store := Some x; y;;
val swap : 'a option ref -> 'a -> 'a = <fun>
We can apply this function to our store
# let one = swap store 1
let one_again = swap store 2
let two = swap store 3;;
val one : int = 1
val one_again : int = 1
val two : int = 2
After these three swaps the stored value is 3. Everything is fine up to now. We can then try to
swap 3 with a more interesting value, for instance a function:
# let error = swap store (fun x -> x);;
Error : This expression should not be a function , the expected type is int
At this point, the type checker rightfully complains that it is not possible to swap an integer and a
function, and that an int should always be traded for another int. Furthermore, the type checker
prevents us to change manually the type of the value stored by store:
# store := Some (fun x -> x);;
Error : This expression should not be a function , the expected type is int
Indeed, looking at the type of store, we see that the weak type '_weak1 has been replaced by the
type int
# store;;
- : int option ref = {contents = Some 3}
Therefore, after placing an int in store, we cannot use it to store any value other than an int.
More generally, weak types protect the program from undue mutation of values with a polymorphic
type.
Moreover, weak types cannot appear in the signature of toplevel modules: types must be known
at compilation time. Otherwise, different compilation units could replace the weak type with
different and incompatible types. For this reason, compiling the following small piece of code
To solve this error, it is enough to add an explicit type annotation to specify the type at
declaration time:
Chapter 6. Polymorphism and its limitations 89
# let f () = [];;
val f : unit -> 'a list = <fun>
# type xy = [ `X | `Y ];;
type xy = [ `X | `Y ]
As x is a subtype of xy, we can convert a value of type x to a value of type xy:
# let x:x = `X;;
val x : x = `X
then depth maps 'a nested values to integers”. There are two major differences with these two
type expressions. First, the explicit polymorphic annotation indicates to the type checker that it
needs to introduce a new type variable every times the function depth is applied. This solves our
problem with the definition of the function depth.
Second, it also notifies the type checker that the type of the function should be polymorphic.
Indeed, without explicit polymorphic type annotation, the following type annotation is perfectly
valid
# let sum: 'a -> 'b -> 'c = fun x y -> x + y;;
val sum : int -> int -> int = <fun>
since 'a,'b and 'c denote type variables that may or may not be polymorphic. Whereas, it is an
error to unify an explicitly polymorphic type with a non-polymorphic type:
# let sum: 'a 'b 'c. 'a -> 'b -> 'c = fun x y -> x + y;;
Error : This definition has type int -> int -> int which is less general than
'a 'b 'c . 'a -> 'b -> 'c
An important remark here is that it is not needed to explicit fully the type of depth: it is
sufficient to add annotations only for the universally quantified type variables:
# let rec depth: 'a. 'a nested -> _ = function
| List _ -> 1
| Nested n -> 1 + depth n;;
val depth : 'a nested -> int = <fun>
- : int = 7
Similarly, it may be necessary to use more than one explicitly polymorphic type variables, like
for computing the nested list of list lengths of the nested list:
# let shape n =
let rec shape: 'a 'b. ('a nested -> int nested) ->
('b list list -> 'a list) -> 'b nested -> int nested
= fun nest nested_shape ->
function
| List l -> raise
(Invalid_argument "shape requires nested_list of depth greater than 1")
| Nested (List l) -> nest @@ List (nested_shape l)
| Nested n ->
let nested_shape = List.map nested_shape in
let nest x = nest (Nested x) in
shape nest nested_shape n in
shape (fun n -> n ) (fun l -> List.map List.length l ) n;;
val shape : 'a nested -> int nested = <fun>
val average: ('a. 'a nested -> int) -> 'a nested -> 'b nested -> int
Note that this syntax is not valid within OCaml: average has an universally quantified type 'a
inside the type of one of its argument whereas for polymorphic recursion the universally quantified
type was introduced before the rest of the type. This position of the universally quantified type
means that average is a second-rank polymorphic function. This kind of higher-rank functions is
not directly supported by OCaml: type inference for second-rank polymorphic function and beyond
is undecidable; therefore using this kind of higher-rank functions requires to handle manually these
universally quantified types.
In OCaml, there are two ways to introduce this kind of explicit universally quantified types:
universally quantified record fields,
# type 'a nested_reduction = { f:'elt. 'elt nested -> 'a };;
type 'a nested_reduction = { f : 'elt. 'elt nested -> 'a; }
Generalized algebraic datatypes, or GADTs, extend usual sum types in two ways: constraints on
type parameters may change depending on the value constructor, and some type variables may be
existentially quantified. Adding constraints is done by giving an explicit return type, where type
parameters are instantiated:
type _ term =
| Int : int -> int term
| Add : (int -> int -> int) term
| App : ('b -> 'a) term * 'b term -> 'a term
This return type must use the same type constructor as the type being defined, and have the
same number of parameters. Variables are made existential when they appear inside a constructor’s
argument, but not in its return type. Since the use of a return type often eliminates the need to name
type parameters in the left-hand side of a type definition, one can replace them with anonymous
types _ in that case.
The constraints associated to each constructor can be recovered through pattern-matching.
Namely, if the type of the scrutinee of a pattern-matching contains a locally abstract type, this
type can be refined according to the constructor used. These extra constraints are only valid inside
the corresponding branch of the pattern-matching. If a constructor has some existential variables,
fresh locally abstract types are generated, and they must not escape the scope of this branch.
97
98
It is important to remark that the function eval is using the polymorphic syntax for locally ab-
stract types. When defining a recursive function that manipulates a GADT, explicit polymorphic
recursion should generally be used. For instance, the following definition fails with a type error:
let rec eval (type a) : a term -> a = function
| Int n -> n
| Add -> (fun x y -> x+y)
| App(f,x) -> (eval f) (eval x)
Error : This expression has type ($App_ ' b -> a ) term
but an expression was expected of type 'a
The type constructor $App_ ' b would escape its scope
In absence of an explicit polymorphic annotation, a monomorphic type is inferred for the recursive
function. If a recursive call occurs inside the function definition at a type that involves an existential
GADT type variable, this variable flows to the type of the recursive function, and thus escapes its
scope. In the above example, this happens in the branch App(f,x) when eval is called with f as
an argument. In this branch, the type of f is ($App_ 'b-> a). The prefix $ in $App_ 'b denotes
an existential type named by the compiler (see 7.5). Since the type of eval is 'a term -> 'a, the
call eval f makes the existential type $App_'b flow to the type variable 'a and escape its scope.
This triggers the above error.
Here is an example of a polymorphic function that takes the runtime representation of some
type t and a value of the same type, then pretty-prints the value as a string:
type _ typ =
| Int : int typ
| String : string typ
| Pair : 'a typ * 'b typ -> ('a * 'b) typ
• $Constr_'a denotes an existential type introduced for the type variable 'a of the GADT
constructor Constr:
type any = Any : 'name -> any
let escape (Any x) = x
Error : This expression has type $Any_ ' name
but an expression was expected of type 'a
The type constructor $Any_ ' name would escape its scope
• $Constr denotes an existential type introduced for an anonymous type variable in the GADT
constructor Constr:
type any = Any : _ -> any
let escape (Any x) = x
Error : This expression has type $Any but an expression was expected of type
'a
The type constructor $Any would escape its scope
• $'a if the existential variable was unified with the type variable 'a during typing:
type ('arg,'result,'aux) fn =
| Fun: ('a ->'b) -> ('a,'b,unit) fn
| Mem1: ('a ->'b) * 'a * 'b -> ('a, 'b, 'a * 'b) fn
let apply: ('arg,'result, _ ) fn -> 'arg -> 'result = fun f x ->
match f with
| Fun f -> f x
| Mem1 (f,y,fy) -> if x = y then fy else f x
Error : This pattern matches values of type
($'arg , ' result , $' arg * ' result ) fn
but a pattern was expected which matches values of type
($'arg , ' result , unit ) fn
The type constructor $' arg would escape its scope
• $n (n a number) is an internally generated existential which could not be named using one of
the previous schemes.
As shown by the last item, the current behavior is imperfect and may be improved in future
versions.
102
In this chapter, we show some larger examples using objects, classes and modules. We review
many of the object features simultaneously on the example of a bank account. We show how modules
taken from the standard library can be expressed as classes. Lastly, we describe a programming
pattern known as virtual types through the example of window managers.
# class account =
object
val mutable balance = zero
method balance = balance
method deposit x = balance <- balance # plus x
method withdraw x =
if x#leq balance then (balance <- balance # plus (neg x); x) else zero
end;;
103
104
class account :
object
val mutable balance : Euro.c
method balance : Euro.c
method deposit : Euro.c -> unit
method withdraw : Euro.c -> Euro.c
end
method deposit x =
if zero#leq x then unsafe # deposit x
else raise (Invalid_argument "deposit")
end;;
class safe_account :
object
val mutable balance : Euro.c
method balance : Euro.c
method deposit : Euro.c -> unit
method withdraw : Euro.c -> Euro.c
end
In particular, this does not require the knowledge of the implementation of the method deposit.
To keep track of operations, we extend the class with a mutable field history and a private
method trace to add an operation in the log. Then each method to be traced is redefined.
# type 'a operation = Deposit of 'a | Retrieval of 'a;;
type 'a operation = Deposit of 'a | Retrieval of 'a
# class account_with_history =
object (self)
inherit safe_account as super
val mutable history = []
method private trace x = history <- x :: history
method deposit x = self#trace (Deposit x); super#deposit x
method withdraw x = self#trace (Retrieval x); super#withdraw x
method history = List.rev history
end;;
class account_with_history :
object
val mutable balance : Euro.c
val mutable history : Euro.c operation list
method balance : Euro.c
method deposit : Euro.c -> unit
method history : Euro.c operation list
method private trace : Euro.c operation -> unit
method withdraw : Euro.c -> Euro.c
end
One may wish to open an account and simultaneously deposit some initial amount. Although the
initial implementation did not address this requirement, it can be achieved by using an initial-
izer.
# class account_with_deposit x =
object
inherit account_with_history
initializer balance <- x
end;;
class account_with_deposit :
Euro.c ->
106
object
val mutable balance : Euro.c
val mutable history : Euro.c operation list
method balance : Euro.c
method deposit : Euro.c -> unit
method history : Euro.c operation list
method private trace : Euro.c operation -> unit
method withdraw : Euro.c -> Euro.c
end
A better alternative is:
# class account_with_deposit x =
object (self)
inherit account_with_history
initializer self#deposit x
end;;
class account_with_deposit :
Euro.c ->
object
val mutable balance : Euro.c
val mutable history : Euro.c operation list
method balance : Euro.c
method deposit : Euro.c -> unit
method history : Euro.c operation list
method private trace : Euro.c operation -> unit
method withdraw : Euro.c -> Euro.c
end
Indeed, the latter is safer since the call to deposit will automatically benefit from safety checks
and from the trace. Let’s test it:
# let ccp = new account_with_deposit (euro 100.) in
let _balance = ccp#withdraw (euro 50.) in
ccp#history;;
- : Euro.c operation list = [Deposit <obj>; Retrieval <obj>]
Closing an account can be done with the following polymorphic function:
# let close c = c#withdraw c#balance;;
val close : < balance : 'a; withdraw : 'a -> 'b; .. > -> 'b = <fun>
Of course, this applies to all sorts of accounts.
Finally, we gather several versions of the account into a module Account abstracted over some
currency.
# let today () = (01,01,2000) (∗ an approximation ∗)
module Account (M:MONEY) =
struct
type m = M.c
let m = new M.c
let zero = m 0.
Chapter 8. Advanced examples with classes and modules 107
class bank =
object (self)
val mutable balance = zero
method balance = balance
val mutable history = []
method private trace x = history <- x::history
method deposit x =
self#trace (Deposit x);
if zero#leq x then balance <- balance # plus x
else raise (Invalid_argument "deposit")
method withdraw x =
if x#leq balance then
(balance <- balance # plus (neg x); self#trace (Retrieval x); x)
else zero
method history = List.rev history
end
let discount x =
let c = new account x in
if today() < (1998,10,30) then c # deposit (m 100.); c
108
end
end;;
This shows the use of modules to group several class definitions that can in fact be thought of as
a single unit. This unit would be provided by a bank for both internal and external uses. This is
implemented as a functor that abstracts over the currency so that the same code can be used to
provide accounts in different currencies.
The class bank is the real implementation of the bank account (it could have been inlined).
This is the one that will be used for further extensions, refinements, etc. Conversely, the client will
only be given the client view.
# module Euro_account = Account(Euro);;
# module Client = Euro_account.Client (Euro_account);;
# new Client.account (new Euro.c 100.);;
Hence, the clients do not have direct access to the balance, nor the history of their own accounts.
Their only way to change their balance is to deposit or withdraw money. It is important to give
the clients a class and not just the ability to create accounts (such as the promotional discount
account), so that they can personalize their account. For instance, a client may refine the deposit
and withdraw methods so as to do his own financial bookkeeping, automatically. On the other
hand, the function discount is given as such, with no possibility for further personalization.
It is important to provide the client’s view as a functor Client so that client accounts can still
be built after a possible specialization of the bank. The functor Client may remain unchanged
and be passed the new definition to initialize a client’s view of the extended account.
# module Investment_account (M : MONEY) =
struct
type m = M.c
module A = Account(M)
class bank =
object
inherit A.bank as super
method deposit x =
if (new M.c 1000.)#leq x then
print_string "Would you like to invest?";
super#deposit x
end
class bank =
object
inherit A.bank
method mail s = print_string s
end
8.2.1 Strings
A naive definition of strings as objects could be:
# class ostring s =
object
method get n = String.get s n
method print = print_string s
method escaped = new ostring (String.escaped s)
end;;
class ostring :
string ->
object
110
8.2.2 Stacks
There is sometimes an alternative between using modules or classes for parametric data types.
Indeed, there are situations when the two approaches are quite similar. For instance, a stack can
be straightforwardly implemented as a class:
# exception Empty;;
exception Empty
# s#fold ( + ) 0;;
- : int = 0
# s;;
- : (int, int) stack2 = <obj>
A better solution is to use polymorphic methods, which were introduced in OCaml version 3.05.
Polymorphic methods makes it possible to treat the type variable 'b in the type of fold as univer-
sally quantified, giving fold the polymorphic type Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b.
An explicit type declaration on the method fold is required, since the type checker cannot infer
the polymorphic type by itself.
# class ['a] stack3 =
object
inherit ['a] stack
method fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b
= fun f x -> List.fold_left f x l
end;;
Chapter 8. Advanced examples with classes and modules 113
8.2.3 Hashtbl
A simplified version of object-oriented hash tables should have the following class type.
# class type ['a, 'b] hash_table =
object
method find : 'a -> 'b
method add : 'a -> 'b -> unit
end;;
class type ['a, 'b] hash_table =
object method add : 'a -> 'b -> unit method find : 'a -> 'b end
A simple implementation, which is quite reasonable for small hash tables is to use an association
list:
# class ['a, 'b] small_hashtbl : ['a, 'b] hash_table =
object
val mutable table = []
method find key = List.assoc key table
method add key value = table <- (key, value) :: table
end;;
class ['a, 'b] small_hashtbl : ['a, 'b] hash_table
A better implementation, and one that scales up better, is to use a true hash table. . . whose
elements are small hash tables!
# class ['a, 'b] hashtbl size : ['a, 'b] hash_table =
object (self)
val table = Array.init size (fun i -> new small_hashtbl)
method private hash key =
(Hashtbl.hash key) mod (Array.length table)
method find key = table.(self#hash key) # find key
method add key = table.(self#hash key) # add key
end;;
class ['a, 'b] hashtbl : int -> ['a, 'b] hash_table
8.2.4 Sets
Implementing sets leads to another difficulty. Indeed, the method union needs to be able to access
the internal representation of another object of the same class.
114
This is another instance of friend functions as seen in section 3.17. Indeed, this is the same
mechanism used in the module Set in the absence of objects.
In the object-oriented version of sets, we only need to add an additional method tag to return
the representation of a set. Since sets are parametric in the type of elements, the method tag has a
parametric type 'a tag, concrete within the module definition but abstract in its signature. From
outside, it will then be guaranteed that two objects with a method tag of the same type will share
the same representation.
# module type SET =
sig
type 'a tag
class ['a] c :
object ('b)
method is_empty : bool
method mem : 'a -> bool
method add : 'a -> 'b
method union : 'b -> 'b
method iter : ('a -> unit) -> unit
method tag : 'a tag
end
end;;
# module Set : SET =
struct
let rec merge l1 l2 =
match l1 with
[] -> l2
| h1 :: t1 ->
match l2 with
[] -> l1
| h2 :: t2 ->
if h1 < h2 then h1 :: merge t1 l2
else if h1 > h2 then h2 :: merge l1 t2
else merge t1 l2
type 'a tag = 'a list
class ['a] c =
object (_ : 'b)
val repr = ([] : 'a list)
method is_empty = (repr = [])
method mem x = List.exists (( = ) x) repr
method add x = {< repr = merge [x] repr >}
method union (s : 'b) = {< repr = merge repr s#tag >}
method iter (f : 'a -> unit) = List.iter f repr
method tag = repr
end
end;;
Chapter 8. Advanced examples with classes and modules 115
object (self)
inherit ['observer, event] subject
val mutable position = 0
method identity = id
method move x = position <- position + x; self#notify_observers Move
method draw = Printf.printf "{Position = %d}\n" position;
end;;
class ['a] window_subject :
object ('b)
constraint 'a = < notify : 'b -> event -> unit; .. >
val mutable observers : 'a list
val mutable position : int
method add_observer : 'a -> unit
method draw : unit
method identity : int
method move : int -> unit
method notify_observers : event -> unit
end
# window#add_observer window_observer;;
- : unit = ()
# window#move 1;;
{Position = 1}
- : unit = ()
Classes window_observer and window_subject can still be extended by inheritance. For in-
stance, one may enrich the subject with new behaviors and refine the behavior of the observer.
Chapter 8. Advanced examples with classes and modules 117
end
and attach several observers to the same object:
# let window = new richer_window_subject;;
val window :
< notify : 'a -> event -> unit; _.. > richer_window_subject as 'a = <obj>
119
Chapter 9
Foreword
This document is intended as a reference manual for the OCaml 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. A good working knowledge of OCaml 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 brackets with a trailing plus sign { . . .}+ denote one or several
repetitions of the enclosed components. Parentheses ( . . .) denote grouping.
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.
(∗ single line comment ∗)
121
122
Identifiers
ident ::= (letter | _) {letter | 0 . . . 9 | _ | '}
capitalized-ident ::= (A . . . Z) {letter | 0 . . . 9 | _ | '}
lowercase-ident ::= (a . . . z | _) {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 or an underscore. Letters contain at least the 52 lowercase and uppercase
letters from the ASCII set. The current implementation also recognizes as letters some characters
from the ISO 8859-1 set (characters 192–214 and 216–222 as uppercase letters; characters 223–246
and 248–255 as lowercase letters). This feature is deprecated and should be avoided for future
compatibility.
All characters in an identifier are meaningful. The current implementation accepts identifiers
up to 16000000 characters in length.
In many places, OCaml makes a distinction between capitalized identifiers and identifiers that
begin with a lowercase letter. The underscore character is considered a lowercase letter for this
purpose.
Integer literals
integer-literal ::= [-] (0 . . . 9) {0 . . . 9 | _}
| [-] (0x | 0X) (0 . . . 9 | A . . . F | a . . . f) {0 . . . 9 | A . . . F | a . . . f | _}
| [-] (0o | 0O) (0 . . . 7) {0 . . . 7 | _}
| [-] (0b | 0B) (0 . . . 1) {0 . . . 1 | _}
int32-literal ::= integer-literal l
int64-literal ::= integer-literal L
nativeint-literal ::= integer-literal n
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)
Chapter 9. The OCaml language 123
(The initial 0 is the digit zero; the O for octal is the letter O.) An integer literal can be followed
by one of the letters l, L or n to indicate that this integer has type int32, int64 or nativeint
respectively, instead of the default type int for integer literals. The interpretation of integer literals
that fall outside the range of representable integer values is undefined.
For convenience and readability, underscore characters (_) are accepted (and ignored) within
integer literals.
# let house_number = 37
let million = 1_000_000
let copyright = 0x00A9
let counter64bit = ref 0L;;
val house_number : int = 37
val million : int = 1000000
val copyright : int = 169
val counter64bit : int64 ref = {contents = 0L}
Floating-point literals
float-literal ::= [-] (0 . . . 9) {0 . . . 9 | _} [. {0 . . . 9 | _}] [(e | E) [+ | -] (0 . . . 9) {0 . . . 9 | _}]
| [-] (0x | 0X) (0 . . . 9 | A . . . F | a . . . f) {0 . . . 9 | A . . . F | a . . . f | _}
[. {0 . . . 9 | A . . . F | a . . . f | _}] [(p | P) [+ | -] (0 . . . 9) {0 . . . 9 | _}]
Floating-point decimal literals consist in an integer part, a fractional part and an exponent
part. The integer part is a sequence of one or more digits, optionally preceded by a minus sign.
The fractional 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. It is
interpreted as a power of 10. The fractional 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.
Floating-point hexadecimal literals are denoted with the 0x or 0X prefix. The syntax is similar
to that of floating-point decimal literals, with the following differences. The integer part and the
fractional part use hexadecimal digits. The exponent part starts with the character p or P. It is
written in decimal and interpreted as a power of 2.
For convenience and readability, underscore characters (_) are accepted (and ignored) within
floating-point literals.
# let pi = 3.141_592_653_589_793_12
let small_negative = -1e-5
let machine_epsilon = 0x1p-52;;
val pi : float = 3.14159265358979312
val small_negative : float = -1e-05
val machine_epsilon : float = 2.22044604925031308e-16
124
Character literals
char-literal ::= ' regular-char '
| ' escape-sequence '
escape-sequence ::= \ (\ | " | ' | n | t | b | r | space)
| \ (0 . . . 9) (0 . . . 9) (0 . . . 9)
| \x (0 . . . 9 | A . . . F | a . . . f) (0 . . . 9 | A . . . F | a . . . f)
| \o (0 . . . 3) (0 . . . 7) (0 . . . 7)
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:
# let a = 'a'
let single_quote = '\''
let copyright = '\xA9';;
val a : char = 'a'
val single_quote : char = '\''
val copyright : char = '\169'
String literals
string-literal ::= " {string-character} "
| { quoted-string-id | {any-char} | quoted-string-id }
quoted-string-id ::= {a... z | _}
string-character ::= regular-string-char
| escape-sequence
| \u{ {0 . . . 9 | A . . . F | a . . . f}+ }
| \ newline {space | tab}
String literals are delimited by " (double quote) characters. The two double quotes enclose a
sequence of either characters different from " and \, or escape sequences from the table given above
for character literals, or a Unicode character escape sequence.
Chapter 9. The OCaml language 125
A Unicode character escape sequence is substituted by the UTF-8 encoding of the specified
Unicode scalar value. The Unicode scalar value, an integer in the ranges 0x0000...0xD7FF or
0xE000...0x10FFFF, is defined using 1 to 6 hexadecimal digits; leading zeros are allowed.
# let greeting = "Hello, World!\n"
let superscript_plus = "\u{207A}";;
val greeting : string = "Hello, World!\n"
val superscript_plus : string = "+ "
To allow splitting long string literals across lines, the sequence \newline spaces-or-tabs (a back-
slash at the end of a line followed by any number of spaces and horizontal tabulations at the
beginning of the next line) is ignored inside string literals.
# let longstr =
"Call me Ishmael. Some years ago –- never mind how long \
precisely –- having little or no money in my purse, and \
nothing particular to interest me on shore, I thought I\
\ would sail about a little and see the watery part of t\
he world.";;
val longstr : string =
"Call me Ishmael. Some years ago –- never mind how long precisely –- having little or no money in my p
Quoted string literals provide an alternative lexical syntax for string literals. They are useful to
represent strings of arbitrary content without escaping. Quoted strings are delimited by a matching
pair of { quoted-string-id | and | quoted-string-id } with the same quoted-string-id on both sides.
Quoted strings do not interpret any character in a special way but requires that the sequence
| quoted-string-id } does not occur in the string itself. The identifier quoted-string-id is a (possibly
empty) sequence of lowercase letters and underscores that can be freely chosen to avoid such issue.
# let quoted_greeting = {|"Hello, World!"|}
let nested = {ext|hello {|world|}|ext};;
val quoted_greeting : string = "\"Hello, World!\""
val nested : string = "hello {|world|}"
The current implementation places practically no restrictions on the length of string literals.
Naming labels
To avoid ambiguities, naming labels in expressions cannot just be defined syntactically as the
sequence of the three tokens ~, ident and :, and have to be defined at the lexical level.
Naming labels come in two flavours: label for normal arguments and optlabel for optional ones.
They are simply distinguished by their first character, either ~ or ?.
Despite label and optlabel being lexical entities in expressions, their expansions ~ label-name :
and ? label-name : will be used in grammars, for the sake of readability. Note also that inside
126
type expressions, this expansion can be taken literally, i.e. there are really 3 tokens, with optional
blanks between them.
Keywords
The identifiers below are reserved as keywords, and cannot be employed otherwise:
Note that the following identifiers are keywords of the now unmaintained Camlp4 system and
should be avoided for backwards compatibility reasons.
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.
Preprocessors that generate OCaml source code can insert line number directives in their output
so that error messages produced by the compiler contain line numbers and file names referring to
the source file before preprocessing, instead of after preprocessing. A line number directive starts
at the beginning of a line, is composed of a # (sharp sign), followed by a positive integer (the source
line number), followed by a character string (the source file name). Line number directives are
treated as blanks during lexical analysis.
9.2 Values
This section describes the kinds of values that are manipulated by OCaml programs.
Floating-point numbers
Floating-point values are numbers in floating-point representation. The current implementation
uses double-precision floating-point numbers conforming to the IEEE 754 standard, with 53 bits of
mantissa and an exponent ranging from −1022 to 1023.
Characters
Character values are represented as 8-bit integers between 0 and 255. Character codes between
0 and 127 are interpreted following the ASCII standard. The current implementation interprets
character codes between 128 and 255 following the ISO 8859-1 standard.
Character strings
String values are finite sequences of characters. The current implementation supports strings con-
taining up to 224 − 5 characters (16777211 characters); on 64-bit platforms, the limit is 257 − 9.
128
9.2.2 Tuples
Tuples of values are written (v 1 , . . . ,v n ), standing for the n-tuple of values v 1 to v n . The current
implementation supports tuple of up to 222 − 1 elements (4194303 elements).
9.2.3 Records
Record values are labeled tuples of values. The record value written { field 1 =v 1 ; . . . ; field n =v n }
associates the value v i to the record field field i , for i = 1 . . . n. The current implementation supports
records with up to 222 − 1 fields (4194303 fields).
9.2.4 Arrays
Arrays are finite, variable-sized sequences of values of the same type. The current implementation
supports arrays containing up to 222 − 1 elements (4194303 elements) unless the elements are
floating-point numbers (2097151 elements in this case); on 64-bit platforms, the limit is 254 − 1 for
all arrays.
Constant Constructor
false the boolean false
true the boolean true
() the “unit” value
[] the empty list
The current implementation limits each variant type to have at most 246 non-constant con-
structors and 230 − 1 constant constructors.
9.2.7 Functions
Functional values are mappings from values to values.
Chapter 9. The OCaml language 129
9.2.8 Objects
Objects are composed of a hidden internal state which is a record of instance variables, and a set
of methods for accessing and modifying these variables. The structure of an object is described by
the toplevel class that created it.
9.3 Names
Identifiers are used to give names to several classes of language objects and refer to these objects
by name later:
These eleven name spaces are distinguished both by the context and by the capitalization of the
identifier: whether the first letter of the identifier is in lowercase (written lowercase-ident below)
or in uppercase (written capitalized-ident). Underscore is considered a lowercase letter for this
purpose.
130
Naming objects
value-name ::= lowercase-ident
| ( operator-name )
operator-name ::= prefix-symbol | infix-op
infix-op ::= infix-symbol
| * | + | - | -. | = | != | < | > | or | || | & | && | :=
| mod | land | lor | lxor | lsl | lsr | asr
constr-name ::= capitalized-ident
tag-name ::= capitalized-ident
typeconstr-name ::= lowercase-ident
field-name ::= lowercase-ident
module-name ::= capitalized-ident
modtype-name ::= ident
class-name ::= lowercase-ident
inst-var-name ::= lowercase-ident
method-name ::= lowercase-ident
See also the following language extension: extended indexing operators.
As shown above, prefix and infix symbols as well as some keywords can be used as value names,
provided they are written between parentheses. The capitalization rules are summarized in the
table below.
Note on polymorphic variant tags: the current implementation accepts lowercase variant tags in
addition to capitalized variant tags, but we suggest you avoid lowercase variant tags for portability
and compatibility with future OCaml versions.
Chapter 9. The OCaml language 131
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 name 1 . name 2 . . ., in case the defining module is itself
nested inside other modules. For referring to type constructors, module types, or class types, the
prefix can also contain simple functor applications (as in the syntactic class extended-module-path
above) in case the defining module is the result of a functor application.
Label names, tag names, method names and instance variable names need not be qualified: the
former three are global labels, while the latter are local to a class.
132
Operator Associativity
Type constructor application –
# –
* –
-> right
as –
Type expressions denote types in definitions of data types as well as in type constraints over
patterns and expressions.
Type variables
The type expression ' ident stands for the type variable named ident. The type expression _ stands
for either an anonymous type variable or anonymous type parameters. In data type definitions, type
variables are names for the data type parameters. In type constraints, they represent unspecified
types that can be instantiated by any type to satisfy the type constraint. In general the scope of a
named type variable is the whole top-level phrase where it appears, and it can only be generalized
when leaving this scope. Anonymous variables have no such restriction. In the following cases,
the scope of named type variables is restricted to the type expression where they appear: 1) for
universal (explicitly polymorphic) type variables; 2) for type variables that only appear in public
method specifications (as those variables will be made universal, as described in section 9.9.1); 3)
Chapter 9. The OCaml language 133
for variables used as aliases, when the type they are aliased to would be invalid in the scope of the
enclosing definition (i.e. when it contains free universal type variables, or locally defined types.)
Parenthesized types
The type expression ( typexpr ) denotes the same type as typexpr.
Function types
The type expression typexpr 1 -> typexpr 2 denotes the type of functions mapping arguments of
type typexpr 1 to results of type typexpr 2 .
label-name : typexpr 1 -> typexpr 2 denotes the same function type, but the argument is labeled
label.
? label-name : typexpr 1 -> typexpr 2 denotes the type of functions mapping an optional labeled
argument of type typexpr 1 to results of type typexpr 2 . That is, the physical type of the function
will be typexpr 1 option -> typexpr 2 .
Tuple types
The type expression typexpr 1 * . . . * typexpr n denotes the type of tuples whose elements belong to
types typexpr 1 , . . . typexpr n 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 pa-
rameter, denotes the application of the unary type constructor typeconstr to the type typexpr.
The type expression (typexpr 1 , . . . , typexpr n ) typeconstr, where typeconstr is a type construc-
tor with n parameters, denotes the application of the n-ary type constructor typeconstr to the
types typexpr 1 through typexpr n .
In the type expression _ typeconstr, the anonymous type expression _ stands in for anony-
mous type parameters and is equivalent to (_, . . . , _) with as many repetitions of _ as the arity of
typeconstr.
Polymorphic variant types describe the values a polymorphic variant may take.
The first case is an exact variant type: all possible tags are known, with their associated types,
and they can all be present. Its structure is fully known.
The second case is an open variant type, describing a polymorphic variant value: it gives the
list of all tags the value could take, with their associated types. This type is still compatible with a
variant type containing more tags. A special case is the unknown type, which does not define any
tag, and is compatible with any variant type.
The third case is a closed variant type. It gives information about all the possible tags and
their associated types, and which tags are known to potentially appear in values. The exact variant
type (first case) is just an abbreviation for a closed variant type where all possible tags are also
potentially present.
In all three cases, tags may be either specified directly in the ` tag-name [of typexpr] form,
or indirectly through a type expression, which must expand to an exact variant type, whose tag
specifications are inserted in its place.
Full specifications of variant tags are only used for non-exact closed types. They can be under-
stood as a conjunctive type for the argument: it is intended to have all the types enumerated in
the specification.
Such conjunctive constraints may be unsatisfiable. In such a case the corresponding tag may
not be used in a value of this type. This does not mean that the whole type is not valid: one can
still use other available tags. Conjunctive constraints are mainly intended as output from the type
checker. When they are used in source programs, unsolvable constraints may cause early failures.
Object types
An object type < [method-type {; method-type}] > is a record of method types.
Each method may have an explicit polymorphic type: {' ident}+ . typexpr. Explicit poly-
morphic variables have a local scope, and an explicit polymorphic type can only be unified to an
equivalent one, where only the order and names of polymorphic variables may change.
The type < {method-type ;} .. > is the type of an object whose method names and types
are described by method-type 1 , . . . , method-type n , and possibly some other methods represented
by the ellipsis. This ellipsis actually is a special kind of type variable (called row variable in the
literature) that stands for any number of extra method types.
Chapter 9. The OCaml language 135
#-types
The type # classtype-path is a special kind of abbreviation. This abbreviation unifies with the type
of any object belonging to a subclass of the class type classtype-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
# classtype-path defines a new type variable, so type # classtype-path -> # classtype-path is usually
not the same as type (# classtype-path as ' ident) -> ' ident.
Use of #-types to abbreviate polymorphic variant types is deprecated. If t is an exact variant
type then #t translates to [<t ], and #t [> ` tag 1 . . . ` tag k ] translates to [<t > ` tag 1 . . . ` tag k ]
9.5 Constants
constant ::= integer-literal
| int32-literal
| int64-literal
| nativeint-literal
| float-literal
| char-literal
| string-literal
| constr
| false
| true
| ()
| begin end
| []
| [| |]
| ` tag-name
See also the following language extension: extension literals.
The syntactic class of constants comprises literals from the four base types (integers, floating-
point numbers, characters, character strings), the integer variants, and constant constructors from
both normal and polymorphic variants, as well as the special constants false, true, ( ), [ ], and
[| |], which behave like constant constructors, and begin end, which is equivalent to ( ).
136
9.6 Patterns
pattern ::= value-name
| _
| constant
| pattern as value-name
| ( pattern )
| ( pattern : typexpr )
| pattern | pattern
| constr pattern
| ` tag-name pattern
| # typeconstr
| pattern {, pattern}+
| { field [: typexpr] [= pattern] {; field [: typexpr] [= pattern]} [; _] [;] }
| [ pattern {; pattern} [;] ]
| pattern :: pattern
| [| pattern {; pattern} [;] |]
| char-literal .. char-literal
| lazy pattern
| exception pattern
| module-path .( pattern )
| module-path .[ pattern ]
| module-path .[| pattern |]
| module-path .{ pattern }
See also the following language extensions: first-class modules, attributes and extension nodes.
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
.. –
lazy (see section 9.6.1) –
Constructor application, Tag application right
:: right
, –
| left
as –
Patterns are templates that allow selecting data structures of a given shape, and binding iden-
tifiers to components of the data structure. This selection operation is called pattern matching;
its outcome is either “this value does not match this pattern”, or “this value matches this pattern,
resulting in the following bindings of names to values”.
Variable patterns
A pattern that consists in a value name matches any value, binding the name to the value. The
pattern _ also matches any value, but does not bind any name.
Chapter 9. The OCaml language 137
Constant patterns
A pattern consisting in a constant matches the values that are equal to this constant.
# let bool_of_string = function
| "true" -> true
| "false" -> false
| _ -> raise (Invalid_argument "bool_of_string");;
val bool_of_string : string -> bool = <fun>
Alias patterns
The pattern pattern1 as value-name matches the same values as pattern1 . If the matching against
pattern1 is successful, the name value-name is bound to the matched value, in addition to the
bindings performed by the matching against pattern1 .
# let sort_pair ((x, y) as p) =
if x <= y then p else (y, x);;
val sort_pair : 'a * 'a -> 'a * 'a = <fun>
Parenthesized patterns
The pattern ( pattern1 ) matches the same values as pattern1 . A type constraint can appear in a
parenthesized pattern, as in ( pattern1 : typexpr ). This constraint forces the type of pattern1 to
be compatible with typexpr.
# let int_triple_is_ordered ((a, b, c) : int * int * int) =
a <= b && b <= c;;
val int_triple_is_ordered : int * int * int -> bool = <fun>
138
“Or” patterns
The pattern pattern1 | pattern2 represents the logical “or” of the two patterns pattern1 and
pattern2 . A value matches pattern1 | pattern2 if it matches pattern1 or pattern2 . The two
sub-patterns pattern1 and pattern2 must bind exactly the same identifiers to values having the
same types. Matching is performed from left to right. More precisely, in case some value v
matches pattern1 | pattern2 , the bindings performed are those of pattern1 when v matches pattern1 .
Otherwise, value v matches pattern2 whose bindings are performed.
# type shape = Square of float | Rect of (float * float) | Circle of float
Variant patterns
The pattern constr ( pattern1 , . . . , patternn ) matches all variants whose constructor is equal to
constr, and whose arguments match pattern1 . . . patternn . It is a type error if n is not the number
of arguments expected by the constructor.
The pattern constr _ matches all variants whose constructor is constr.
# type 'a tree = Lf | Br of 'a tree * 'a * 'a tree
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.
# let vector (x0, y0) (x1, y1) =
(x1 -. x0, y1 -. y0);;
val vector : float * float -> float * float -> float * float = <fun>
Record patterns
The pattern { field 1 [= pattern1 ] ; . . . ; field n [= patternn ] } matches records that define at least the
fields field 1 through field n , and such that the value associated to field i matches the pattern patterni ,
for i = 1, . . . , n. A single identifier field k stands for field k = field k , and a single qualified identifier
module-path . field k stands for module-path . field k = field k . The record value can define more
fields than field 1 . . . field n ; the values associated to these extra fields are not taken into account for
140
matching. Optionally, a record pattern can be terminated by ; _ to convey the fact that not all fields
of the record type are listed in the record pattern and that it is intentional. Optional type constraints
can be added field by field with { field 1 : typexpr 1 = pattern1 ; . . . ; field n : typexpr n = patternn }
to force the type of field k to be compatible with typexpr k .
# let bytes_allocated
{Gc.minor_words = minor;
Gc.major_words = major;
Gc.promoted_words = prom;
_}
=
(Sys.word_size / 4) * int_of_float (minor +. major -. prom);;
val bytes_allocated : Gc.stat -> int = <fun>
Array patterns
The pattern [| pattern1 ; . . . ; patternn |] matches arrays of length n such that the i-th array
element matches the pattern patterni , for i = 1, . . . , n.
# let matrix3_is_symmetric = function
| [|[|_; b; c|];
[|d; _; f|];
[|g; h; _|]|] -> b = d && c = g && f = h
| _ -> failwith "matrix3_is_symmetric: not a 3x3 matrix";;
val matrix3_is_symmetric : 'a array array -> bool = <fun>
Range patterns
The pattern 'c ' .. 'd ' is a shorthand for the pattern
'c ' | 'c 1 ' | 'c 2 ' | . . . | 'c n ' | '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.
# type char_class = Uppercase | Lowercase | Digit | Other
The pattern lazy pattern matches a value v of type Lazy.t, provided pattern matches the
result of forcing v with Lazy.force. A successful match of a pattern containing lazy sub-patterns
forces the corresponding parts of the value being matched, even those that imply no test such
as lazy value-name or lazy _. Matching a value with a pattern-matching where some patterns
contain lazy sub-patterns may imply forcing parts of the value, even when the pattern selected in
the end has no lazy sub-pattern.
# let force_opt = function
| Some (lazy n) -> n
| None -> 0;;
val force_opt : int lazy_t option -> int = <fun>
For more information, see the description of module Lazy in the standard library (module
Lazy[25.26]).
Exception patterns
(Introduced in OCaml 4.02)
A new form of exception pattern, exception pattern, is allowed only as a toplevel pattern or
inside a toplevel or-pattern under a match...with pattern-matching (other occurrences are rejected
by the type-checker).
Cases with such a toplevel pattern are called “exception cases”, as opposed to regular “value
cases”. Exception cases are applied when the evaluation of the matched expression raises an excep-
tion. The exception value is then matched against all the exception cases and re-raised if none of
them accept the exception (as with a try...with block). Since the bodies of all exception and value
cases are outside the scope of the exception handler, they are all considered to be in tail-position:
if the match...with block itself is in tail position in the current function, any function call in tail
position in one of the case bodies results in an actual tail call.
A pattern match must contain at least one value case. It is an error if all cases are exceptions,
because there would be no code to handle the return of a value.
# let find_opt p l =
match List.find p l with
| exception Not_found -> None
| x -> Some x;;
val find_opt : ('a -> bool) -> 'a list -> 'a option = <fun>
For patterns, local opens are limited to the module-path .( pattern ) construction. This
construction locally opens the module referred to by the module path module-path in the scope of
the pattern pattern.
When the body of a local open pattern is delimited by [ ], [| |], or { }, the parentheses can
be omitted. For example, module-path .[ pattern ] is equivalent to module-path .([ pattern ]),
and module-path .[| pattern |] is equivalent to module-path .([| pattern |]).
# let bytes_allocated Gc.{minor_words; major_words; promoted_words; _} =
(Sys.word_size / 4)
* int_of_float (minor_words +. major_words -. promoted_words);;
val bytes_allocated : Gc.stat -> int = <fun>
Chapter 9. The OCaml language 143
9.7 Expressions
expr ::= value-path
| constant
| ( expr )
| begin expr end
| ( expr : typexpr )
| expr {, expr}+
| constr expr
| ` tag-name expr
| expr :: expr
| [ expr {; expr} [;] ]
| [| expr {; expr} [;] |]
| { field [: typexpr] [= expr] {; field [: typexpr] [= expr]} [;] }
| { expr with field [: typexpr] [= expr] {; field [: typexpr] [= expr]} [;] }
| expr {argument}+
| prefix-symbol expr
| - expr
| -. expr
| expr infix-op expr
| expr . field
| expr . field <- expr
| expr .( expr )
| expr .( expr ) <- expr
| expr .[ expr ]
| expr .[ expr ] <- expr
| if expr then expr [else expr]
| while expr do expr done
| for value-name = expr (to | downto) expr do expr done
| expr ; expr
| match expr with pattern-matching
| function pattern-matching
| fun {parameter}+ [: typexpr] -> expr
| try expr with pattern-matching
| let [rec] let-binding {and let-binding} in expr
| let exception constr-decl in expr
| let module module-name {( module-name : module-type )} [: module-type]
= module-expr in expr
| ( expr :> typexpr )
| ( expr : typexpr :> typexpr )
| assert expr
| lazy expr
| local-open
| object-expr
144
Value paths
An expression consisting in an access path evaluates to the value bound to this path in the cur-
rent evaluation environment. The path can be either a value name or an access path to a value
component of a module.
# Float.ArrayLabels.to_list;;
- : Float.ArrayLabels.t -> float list = <fun>
Parenthesized expressions
The expressions ( expr ) and begin expr end have the same value as expr. The two constructs are
semantically equivalent, but it is good style to use begin . . . end inside control structures:
if ... then begin ... ; ... end else begin ... ; ... end
# let x = 1 + 2 * 3
let y = (1 + 2) * 3;;
val x : int = 7
val y : int = 9
# let f a b =
if a = b then
print_endline "Equal"
else begin
print_string "Not Equal: ";
print_int a;
print_string " and ";
print_int b;
print_newline ()
end;;
val f : int -> int -> unit = <fun>
Parenthesized expressions can contain a type constraint, as in ( expr : typexpr ). This
constraint forces the type of expr to be compatible with typexpr.
Parenthesized expressions can also contain coercions ( expr [: typexpr] :> typexpr ) (see
subsection 9.7.8 below).
Function application
Function application is denoted by juxtaposition of (possibly labeled) expressions. The expression
expr argument1 . . . argumentn evaluates the expression expr and those appearing in argument1 to
argumentn . The expression expr must evaluate to a functional value f , which is then applied to
the values of argument1 , . . . , argumentn .
The order in which the expressions expr, argument1 , . . . , argumentn are evaluated is not spec-
ified.
# List.fold_left ( + ) 0 [1; 2; 3; 4; 5];;
- : int = 15
Arguments and parameters are matched according to their respective labels. Argument order
is irrelevant, except among arguments with the same label, or no label.
# ListLabels.fold_left ~f:( @ ) ~init:[] [[1; 2; 3]; [4; 5; 6]; [7; 8; 9]];;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]
If a parameter is specified as optional (label prefixed by ?) in the type of expr, the corresponding
argument will be automatically wrapped with the constructor Some, except if the argument itself
is also prefixed by ?, in which case it is passed as is.
# let fullname ?title first second =
match title with
| Some t -> t ^ " " ^ first ^ " " ^ second
| None -> first ^ " " ^ second
Chapter 9. The OCaml language 147
Function definition
Two syntactic forms are provided to define functions. The first form is introduced by the keyword
function:
val bool_map : cmp:(int -> int -> bool) -> int list -> (int -> bool) list =
<fun>
val bool_map' : cmp:(int -> int -> bool) -> int list -> (int -> bool) list =
<fun>
A function of the form fun ? lab :( pattern = expr 0 ) -> expr is equivalent to
fun ? lab : ident -> let pattern = match ident with Some ident -> ident | None -> expr 0 in expr
where ident is a fresh variable, except that it is unspecified when expr 0 is evaluated.
# let open_file_for_input ?binary filename =
match binary with
| Some true -> open_in_bin filename
| Some false | None -> open_in filename
If we ignore labels, which will only be meaningful at function application, this is equivalent to
That is, the fun expression above evaluates to a curried function with n arguments: after applying
this function n times to the values v 1 . . . v n , 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
The cases of a pattern matching (in the function, 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:
Local definitions
The let and let rec constructs bind value names locally. The construct
evaluates expr 1 . . . expr n in some unspecified order and 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.
# let v =
let x = 1 in [x; x; x]
let v' =
let a, b = (1, 2) in a + b
let v'' =
let a = 1 and b = 2 in a + b;;
val v : int list = [1; 1; 1]
val v' : int = 3
val v'' : int = 3
An alternate syntax is provided to bind variables to functional values: instead of writing
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
expr 1 to expr n are evaluated. That is, the expressions expr 1 to expr n 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.
# let rec even =
function 0 -> true | n -> odd (n - 1)
and odd =
function 0 -> false | n -> even (n - 1)
in
even 1000;;
- : bool = true
The recursive definition is guaranteed to behave as described above if the expressions expr 1 to
expr n are function definitions (fun . . . or function . . .), and the patterns pattern1 . . . patternn are
just value names, as in:
These annotations explicitly require the defined value to be polymorphic, and allow one to use
this polymorphism in recursive occurrences (when using let rec). Note however that this is a
normal polymorphic type, unifiable with any instance of itself.
Conditional
The expression if expr 1 then expr 2 else expr 3 evaluates to the value of expr 2 if expr 1 evaluates
to the boolean true, and to the value of expr 3 if expr 1 evaluates to the boolean false.
# let rec factorial x =
if x <= 1 then 1 else x * factorial (x - 1);;
val factorial : int -> int = <fun>
The else expr 3 part can be omitted, in which case it defaults to else ().
# let debug = ref false
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 expr i is evaluated, and its value becomes the value of
the whole match expression. The evaluation of expr i 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.
Chapter 9. The OCaml language 153
Boolean operators
The expression expr 1 && expr 2 evaluates to true if both expr 1 and expr 2 evaluate to true; oth-
erwise, it evaluates to false. The first component, expr 1 , is evaluated first. The second com-
ponent, expr 2 , is not evaluated if the first component evaluates to false. Hence, the expression
expr 1 && expr 2 behaves exactly as
The expression expr 1 || expr 2 evaluates to true if one of the expressions expr 1 and expr 2
evaluates to true; otherwise, it evaluates to false. The first component, expr 1 , is evaluated first.
The second component, expr 2 , is not evaluated if the first component evaluates to true. Hence,
the expression expr 1 || expr 2 behaves exactly as
The boolean operators & and or are deprecated synonyms for (respectively) && and ||.
# let xor a b =
(a || b) && not (a && b);;
val xor : bool -> bool -> bool = <fun>
Loops
The expression while expr 1 do expr 2 done repeatedly evaluates expr 2 while expr 1 evaluates to
true. The loop condition expr 1 is evaluated and tested at the beginning of each iteration. The
whole while . . . done expression evaluates to the unit value ().
# let chars_of_string s =
let i = ref 0 in
let chars = ref [] in
154
Exception handling
The expression
try expr
with pattern1 -> 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
expr i is evaluated, and its value becomes the value of the whole try expression. The evaluation of
expr i 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.
Chapter 9. The OCaml language 155
# let find_opt p l =
try Some (List.find p l) with Not_found -> None;;
val find_opt : ('a -> bool) -> 'a list -> 'a option = <fun>
Variants
The expression constr expr evaluates to the unary variant value whose constructor is constr, and
whose argument is the value of expr. Similarly, the expression constr ( expr 1 , . . . , expr n )
evaluates to the n-ary variant value whose constructor is constr and whose arguments are the
values of expr 1 , . . . , expr n .
The expression constr ( expr 1 , . . . , expr n ) evaluates to the variant value whose constructor is
constr, and whose arguments are the values of expr 1 . . . expr n .
# type t = Var of string | Not of t | And of t * t | Or of t * t
let test = And (Var "x", Not (Or (Var "y", Var "z")));;
type t = Var of string | Not of t | And of t * t | Or of t * t
val test : t = And (Var "x", Not (Or (Var "y", Var "z")))
For lists, some syntactic sugar is provided. The expression expr 1 :: expr 2 stands for the con-
structor ( :: ) applied to the arguments ( expr 1 , expr 2 ), and therefore evaluates to the list whose
head is the value of expr 1 and whose tail is the value of expr 2 . The expression [ expr 1 ; . . . ; expr n ]
is equivalent to expr 1 :: . . . :: expr n :: [], and therefore evaluates to the list whose elements are
the values of expr 1 to expr n .
# 0 :: [1; 2; 3] = 0 :: 1 :: 2 :: 3 :: [];;
- : bool = true
Polymorphic variants
The expression ` tag-name expr evaluates to the polymorphic variant value whose tag is tag-name,
and whose argument is the value of expr.
# let with_counter x = `V (x, ref 0);;
val with_counter : 'a -> [> `V of 'a * int ref ] = <fun>
156
Records
The expression { field 1 [= expr 1 ] ; . . . ; field n [= expr n ]} evaluates to the record value
{f ield1 = v1 ; . . . ; f ieldn = vn } where vi is the value of expr i for i = 1, . . . , n. A single
identifier field k stands for field k = field k , and a qualified identifier module-path . field k
stands for module-path . field k = field k . The fields field 1 to field n must all belong to the
same record type; each field of this record type must appear exactly once in the record
expression, though they can appear in any order. The order in which expr 1 to expr n
are evaluated is not specified. Optional type constraints can be added after each field
{ field 1 : typexpr 1 = expr 1 ; . . . ; field n : typexpr n = expr n } to force the type of field k to be
compatible with typexpr k .
# type t = {house_no : int; street : string; town : string; postcode : string}
let address x =
Printf.sprintf "The occupier\n%i %s\n%s\n%s"
x.house_no x.street x.town x.postcode;;
type t = {
house_no : int;
street : string;
town : string;
postcode : string;
}
val address : t -> string = <fun>
The expression { expr with field 1 [= expr 1 ] ; . . . ; field n [= expr n ] } builds a fresh record
with fields field 1 . . . field n equal to expr 1 . . . expr n , and all other fields having the same value
as in the record expr. In other terms, it returns a shallow copy of the record expr, except
for the fields field 1 . . . field n , which are initialized to expr 1 . . . expr n . As previously, single
identifier field k stands for field k = field k , a qualified identifier module-path . field k stands for
module-path . field k = field k and it is possible to add an optional type constraint on each field
being updated with { expr with field 1 : typexpr 1 = expr 1 ; . . . ; field n : typexpr n = expr n }.
# type t = {house_no : int; street : string; town : string; postcode : string}
is permitted only if field has been declared mutable in the definition of the record type. The whole
expression expr 1 . field <- expr 2 evaluates to the unit value ().
# type t = {mutable upper : int; mutable lower : int; mutable other : int}
let collect =
String.iter
(function
| 'A'..'Z' -> stats.upper <- stats.upper + 1
| 'a'..'z' -> stats.lower <- stats.lower + 1
| _ -> stats.other <- stats.other + 1);;
type t = { mutable upper : int; mutable lower : int; mutable other : int; }
val stats : t = {upper = 0; lower = 0; other = 0}
val collect : string -> unit = <fun>
Arrays
The expression [| expr 1 ; . . . ; expr n |] evaluates to a n-element array, whose elements are ini-
tialized with the values of expr 1 to expr n respectively. The order in which these expressions are
evaluated is unspecified.
The expression expr 1 .( expr 2 ) returns the value of element number expr 2 in the array denoted
by expr 1 . 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 expr 1 .( expr 2 ) <- expr 3 modifies in-place the array denoted by expr 1 , replac-
ing element number expr 2 by the value of expr 3 . The exception Invalid_argument is raised if the
access is out of bounds. The value of the whole expression is ().
# let scale arr n =
for x = 0 to Array.length arr - 1 do
arr.(x) <- arr.(x) * n
done
Strings
The expression expr 1 .[ expr 2 ] returns the value of character number expr 2 in the string denoted
by expr 1 . 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.
# let iter f s =
for x = 0 to String.length s - 1 do f s.[x] done;;
158
val iter : (char -> 'a) -> string -> unit = <fun>
The expression expr 1 .[ expr 2 ] <- expr 3 modifies in-place the string denoted by expr 1 ,
replacing character number expr 2 by the value of expr 3 . The exception Invalid_argument is raised
if the access is out of bounds. The value of the whole expression is (). Note: this possibility is
offered only for backward compatibility with older versions of OCaml and will be removed in a
future version. New code should use byte sequences and the Bytes.set function.
9.7.6 Operators
Symbols from the class infix-symbol, as well as the keywords *, +, -, -., =, !=, <, >, or, ||, &, &&,
:=, mod, land, lor, lxor, lsl, lsr, and asr can appear in infix position (between two expressions).
Symbols from the class prefix-symbol, as well as the keywords - and -. can appear in prefix position
(in front of an expression).
# (( * ), ( := ), ( || ));;
- : (int -> int -> int) * ('a ref -> 'a -> unit) * (bool -> bool -> bool) =
(<fun>, <fun>, <fun>)
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 expr 1 infix-symbol expr 2 is interpreted as the application ( infix-symbol ) expr 1 expr 2 .
The table below lists the symbols defined in the initial environment and their initial meaning.
(See the description of the core library module Stdlib in chapter 24 for more details). Their
meaning may be changed at any time using let ( infix-op ) name 1 name 2 = . . .
# let ( + ), ( - ), ( * ), ( / ) = Int64.(add, sub, mul, div);;
val ( + ) : int64 -> int64 -> int64 = <fun>
val ( - ) : int64 -> int64 -> int64 = <fun>
val ( * ) : int64 -> int64 -> int64 = <fun>
val ( / ) : int64 -> int64 -> int64 = <fun>
Note: the operators &&, ||, and ~- are handled specially and it is not advisable to change their
meaning.
The keywords - and -. can appear both as infix and prefix operators. When they appear as
prefix operators, they are interpreted respectively as the functions (~-) and (~-.).
Chapter 9. The OCaml language 159
9.7.7 Objects
Object creation
When class-path evaluates to a class body, new class-path evaluates to a new object containing the
instance variables and methods of this class.
# class of_list (lst : int list) = object
val mutable l = lst
method next =
match l with
160
Method invocation
The expression expr # method-name invokes the method method-name of the object denoted by
expr.
# class of_list (lst : int list) = object
val mutable l = lst
method next =
match l with
| [] -> raise (Failure "empty list");
| h::t -> l <- t; h
end
Object duplication
An object can be duplicated using the library function Oo.copy (see module Oo[25.34]). 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. A single
instance variable name id stands for id = id. Other instance variables have the same value in the
returned object as in self.
# let o =
object
val secret = 99
val password = "unlock"
method get guess = if guess <> password then None else Some secret
method with_new_secret s = {< secret = s >}
end;;
val o : < get : string -> int option; with_new_secret : int -> 'a > as 'a =
<obj>
162
9.7.8 Coercions
Expressions whose type contains object or polymorphic variant types can be explicitly coerced
(weakened) to a supertype. The expression ( expr :> typexpr ) coerces the expression expr to
type typexpr. The expression ( expr : typexpr 1 :> typexpr 2 ) coerces the expression expr from
type typexpr 1 to type typexpr 2 .
The former operator will sometimes fail to coerce an expression expr from a type typ 1 to a type
typ 2 even if type typ 1 is a subtype of type typ 2 : in the current implementation it only expands two
levels of type abbreviations containing objects and/or polymorphic variants, keeping only recursion
when it is explicit in the class type (for objects). As an exception to the above algorithm, if both the
inferred type of expr and typ are ground (i.e. do not contain type variables), the former operator
behaves as the latter one, taking the inferred type of expr as typ 1 . In case of failure with the former
operator, the latter one should be used.
It is only possible to coerce an expression expr from type typ 1 to type typ 2 , if the type of expr
is an instance of typ 1 (like for a type annotation), and typ 1 is a subtype of typ 2 . The type of the
coerced expression is an instance of typ 2 . If the types contain variables, they may be instantiated
by the subtyping algorithm, but this is only done after determining whether typ 1 is a potential
subtype of typ 2 . This means that typing may fail during this latter unification step, even if some
instance of typ 1 is a subtype of some instance of typ 2 . In the following paragraphs we describe the
subtyping relation used.
Object types
A fixed object type admits as subtype any object type that includes all its methods. The types of
the methods shall be subtypes of those in the supertype. Namely,
is a supertype of
< met1 : typ 01 ; . . . ; metn : typ 0n ; metn+1 : typ 0n+1 ; . . . ; metn+m : typ 0n+m [; ..] >
which may contain an ellipsis .. if every typ i is a supertype of the corresponding typ 0i .
A monomorphic method type can be a supertype of a polymorphic method type. Namely, if
typ is an instance of typ 0 , then 'a 1 . . . 'a n . typ 0 is a subtype of typ.
Inside a class definition, newly defined types are not available for subtyping, as the type abbre-
viations are not yet completely defined. There is an exception for coercing self to the (exact) type
of its class: this is allowed if the type of self does not appear in a contravariant position in the
class type, i.e. if there are no binary methods.
Variance
Other types do not introduce new subtyping, but they may propagate the subtyping of their
arguments. For instance, typ 1 * typ 2 is a subtype of typ 01 * typ 02 when typ 1 and typ 2 are respectively
subtypes of typ 01 and typ 02 . For function types, the relation is more subtle: typ 1 -> typ 2 is a subtype
of typ 01 -> typ 02 if typ 1 is a supertype of typ 01 and typ 2 is a subtype of typ 02 . For this reason, function
types are covariant in their second argument (like tuples), but contravariant in their first argument.
Mutable types, like array or ref are neither covariant nor contravariant, they are nonvariant, that
is they do not propagate subtyping.
For user-defined types, the variance is automatically inferred: a parameter is covariant if it
has only covariant occurrences, contravariant if it has only contravariant occurrences, variance-free
if it has no occurrences, and nonvariant otherwise. A variance-free parameter may change freely
through subtyping, it does not have to be a subtype or a supertype. For abstract and private types,
the variance must be given explicitly (see section 9.8.1), otherwise the default is nonvariant. This
is also the case for constrained arguments in type definitions.
9.7.9 Other
Assertion checking
OCaml supports the assert construct to check debugging assertions. The expression assert expr
evaluates the expression expr and returns () if expr evaluates to true. If it evaluates to false
the exception Assert_failure is raised with the source file name and the location of expr as
arguments. Assertion checking can be turned off with the -noassert compiler option. In this case,
expr is not evaluated at all.
# let f a b c =
assert (a <= b && b <= c);
(b -. a) /. (c -. b);;
val f : float -> float -> float -> float = <fun>
As a special case, assert␣false is reduced to raise (Assert_failure ...), which gives it
a polymorphic type. This means that it can be used in place of any expression (for example as
a branch of any pattern-matching). It also means that the assert␣false “assertions” cannot be
turned off by the -noassert option.
# let min_known_nonempty = function
| [] -> assert false
| l -> List.hd (List.sort compare l);;
val min_known_nonempty : 'a list -> 'a = <fun>
164
Lazy expressions
The expression lazy expr returns a value v of type Lazy.t that encapsulates the computation of
expr. The argument expr is not evaluated at this point in the program. Instead, its evaluation
will be performed the first time the function Lazy.force is applied to the value v, returning the
actual value of expr. Subsequent applications of Lazy.force to v do not evaluate expr again.
Applications of Lazy.force may be implicit through pattern matching (see 9.6.1).
# let lazy_greeter = lazy (print_string "Hello, World!\n");;
val lazy_greeter : unit lazy_t = <lazy>
# Lazy.force lazy_greeter;;
Hello, World!
- : unit = ()
Local modules
The expression let module module-name = module-expr in expr locally binds the module expres-
sion module-expr to the identifier module-name during the evaluation of the expression expr. It
then returns the value of expr. For example:
# let remove_duplicates comparison_fun string_list =
let module StringSet =
Set.Make(struct type t = string
let compare = comparison_fun end)
in
StringSet.elements
(List.fold_right StringSet.add string_list StringSet.empty);;
val remove_duplicates :
(string -> string -> int) -> string list -> string list = <fun>
Local opens
The expressions let open module-path in expr and module-path .( expr ) are strictly equivalent.
These constructions locally open the module referred to by the module path module-path in the
respective scope of the expression expr.
# let map_3d_matrix f m =
let open Array in
map (map (map f)) m
let map_3d_matrix' f =
Array.(map (map (map f)));;
val map_3d_matrix :
('a -> 'b) -> 'a array array array -> 'b array array array = <fun>
val map_3d_matrix' :
('a -> 'b) -> 'a array array array -> 'b array array array = <fun>
Chapter 9. The OCaml language 165
When the body of a local open expression is delimited by [ ], [| |], or { }, the parenthe-
ses can be omitted. For expression, parentheses can also be omitted for {< >}. For example,
module-path .[ expr ] is equivalent to module-path .([ expr ]), and module-path .[| expr |] is
equivalent to module-path .([| expr |]).
# let vector = Random.[|int 255; int 255; int 255; int 255|];;
val vector : int array = [|116; 127; 85; 129|]
See also the following language extensions: private types, generalized algebraic datatypes, at-
tributes, extension nodes, extensible variant types and inline records.
166
Type definitions are introduced by the type keyword, and consist in one or several simple
definitions, possibly mutually recursive, separated by the and keyword. Each simple definition
defines one type constructor.
A simple definition consists in a lowercase identifier, possibly preceded by one or several type
parameters, and followed by an optional type equation, then an optional type representation, and
then a constraint clause. The identifier is the name of the type constructor being defined.
type colour =
| Red | Green | Blue | Yellow | Black | White
| RGB of {r : int; g : int; b : int}
In the right-hand side of type definitions, references to one of the type constructor name being
defined are considered as recursive, unless type is followed by nonrec. The nonrec keyword was
introduced in OCaml 4.02.2.
The optional type parameters are either one type variable ' ident, for type constructors with
one parameter, or a list of type variables (' ident1 , . . . , ' identn ), for type constructors with several
parameters. Each type parameter may be prefixed by a variance constraint + (resp. -) indicating
that the parameter is covariant (resp. contravariant), and an injectivity annotation ! indicating
that the parameter can be deduced from the whole type. These type parameters can appear in
the type expressions of the right-hand side of the definition, optionally restricted by a variance
constraint ; i.e. a covariant parameter may only appear on the right side of a functional arrow
(more precisely, follow the left branch of an even number of arrows), and a contravariant parameter
only the left side (left branch of an odd number of arrows). If the type has a representation or
an equation, and the parameter is free (i.e. not bound via a type constraint to a constructed
type), its variance constraint is checked but subtyping etc. will use the inferred variance of the
parameter, which may be less restrictive; otherwise (i.e. for abstract types or non-free parameters),
the variance must be given explicitly, and the parameter is invariant if no variance is given.
The optional type equation = typexpr makes the defined type equivalent to the type expression
typexpr: one can be substituted for the other during typing. If no type equation is given, a new
type is generated: the defined type is incompatible with any other type.
The optional type representation describes the data structure representing the defined type, by
giving the list of associated constructors (if it is a variant type) or associated fields (if it is a record
type). If no type representation is given, nothing is assumed on the structure of the type besides
what is stated in the optional type equation.
The type representation = [|] constr-decl {| constr-decl} describes a variant type. The construc-
tor declarations constr-decl 1 , . . . , constr-decl n describe the constructors associated to this variant
type. The constructor declaration constr-name of typexpr 1 * . . . * typexpr n declares the name
constr-name as a non-constant constructor, whose arguments have types typexpr 1 . . . typexpr n .
The constructor declaration constr-name declares the name constr-name as a constant constructor.
Constructor names must be capitalized.
Chapter 9. The OCaml language 167
The type representation = { field-decl {; field-decl} [;] } describes a record type. The field
declarations field-decl 1 , . . . , field-decl n describe the fields associated to this record type. The field
declaration field-name : poly-typexpr declares field-name as a field whose argument has type
poly-typexpr. The field declaration mutable field-name : poly-typexpr behaves similarly; in ad-
dition, it allows physical modification of this field. Immutable fields are covariant, mutable fields
are non-variant. Both mutable and immutable fields may have explicitly polymorphic types. The
polymorphism of the contents is statically checked whenever a record value is created or modified.
Extracted values may have their types instantiated.
The two components of a type definition, the optional equation and the optional representation,
can be combined independently, giving rise to four typical situations:
The type variables appearing as type parameters can optionally be prefixed by + or - to indicate
that the type constructor is covariant or contravariant with respect to this parameter. This variance
information is used to decide subtyping relations when checking the validity of :> coercions (see
section 9.7.8).
For instance, type +'a t declares t as an abstract type that is covariant in its parameter;
this means that if the type τ is a subtype of the type σ, then τ t is a subtype of σ t. Similarly,
type -'a t declares that the abstract type t is contravariant in its parameter: if τ is a subtype of
σ, then σ t is a subtype of τ t. If no + or - variance annotation is given, the type constructor is
assumed non-variant in the corresponding parameter. For instance, the abstract type declaration
type 'a t means that τ t is neither a subtype nor a supertype of σ t if τ is subtype of σ.
The variance indicated by the + and - annotations on parameters is enforced only for abstract
and private types, or when there are type constraints. Otherwise, for abbreviations, variant and
record types without type constraints, the variance properties of the type constructor are inferred
168
from its definition, and the variance annotations are only checked for conformance with the defini-
tion.
Injectivity annotations are only necessary for abstract types and private row types, since they
can otherwise be deduced from the type declaration: all parameters are injective for record and
variant type declarations (including extensible types); for type abbreviations a parameter is injective
if it has an injective occurrence in its defining equation (be it private or not). For constrained type
parameters in type abbreviations, they are injective if either they appear at an injective position in
the body, or if all their type variables are injective; in particular, if a constrained type parameter
contains a variable that doesn’t appear in the body, it cannot be injective.
The construct constraint ' ident = typexpr allows the specification of type parameters. Any
actual type argument corresponding to the type parameter ident has to be an instance of typexpr
(more precisely, ident and typexpr are unified). Type variables of typexpr can appear in the type
equation and the type declaration.
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.
# exception E of int * string;;
exception E of int * string
The form exception constr-decl generates a new exception, distinct from all other exceptions
in the system. The form exception constr-name = constr gives an alternate name to an existing
exception.
# exception E of int * string
exception F = E
let eq =
E (1, "one") = F (1, "one");;
exception E of int * string
exception F of int * string
val eq : bool = true
9.9 Classes
Classes are defined using a small language, similar to the module language.
See also the following language extensions: attributes and extension nodes.
Local opens
Local opens are supported in class types since OCaml 4.06.
170
Inheritance
The inheritance construct inherit class-body-type provides for inclusion of methods and instance
variables from other class types. The instance variable and method types from class-body-type are
added into the current class type.
Method specification
The specification of a method is written method [private] method-name : poly-typexpr, where
method-name is the name of the method and poly-typexpr its expected type, possibly polymorphic.
The flag private indicates that the method cannot be accessed from outside the object.
The polymorphism may be left implicit in public method specifications: any type variable which
is not bound to a class parameter and does not appear elsewhere inside the class specification will be
assumed to be universal, and made polymorphic in the resulting method type. Writing an explicit
polymorphic type will disable this behaviour.
If several specifications are present for the same method, they must have compatible types. Any
non-private specification of a method forces it to be public.
Class application
Class application is denoted by juxtaposition of (possibly labeled) expressions. It denotes the
class whose constructor is the first expression applied to the given arguments. The arguments
are evaluated as for expression application, but the constructor itself will only be evaluated when
objects are created. In particular, side-effects caused by the application of the constructor will only
occur at object creation time.
172
Class function
The expression fun [[?] label-name :] pattern -> class-expr evaluates to a function from values
to classes. When this function is applied to a value v, this value is matched against the pattern
pattern and the result is the result of the evaluation of class-expr in the extended environment.
Conversion from functions with default values to functions with patterns only works identically
for class functions as for normal functions.
The expression
fun parameter 1 . . . parameter n -> class-expr
is a short form for
fun parameter 1 -> . . . fun parameter n -> expr
Local definitions
The let and let rec constructs bind value names locally, as for the core language expressions.
If a local definition occurs at the very beginning of a class definition, it will be evaluated when
the class is created (just as if the definition was outside of the class). Otherwise, it will be evaluated
when the object constructor is called.
Local opens
Local opens are supported in class expressions since OCaml 4.06.
Class body
class-body ::= [( pattern [: typexpr] )] {class-field}
The expression object class-body end denotes a class body. This is the prototype for an object :
it lists the instance variables and methods of an object of this class.
A class body is a class value: it is not evaluated at once. Rather, its components are evaluated
each time an object is created.
In a class body, the pattern ( pattern [: typexpr] ) is matched against self, therefore providing
a binding for self and self type. Self can only be used in method and initializers.
Self type cannot be a closed object type, so that the class remains extensible.
Since OCaml 4.01, it is an error if the same method or instance variable name is defined several
times in the same class body.
Inheritance
The inheritance construct inherit class-expr allows reusing methods and instance variables from
other classes. The class expression class-expr must evaluate to a class body. The instance variables,
methods and initializers from this class body are added into the current class. The addition of a
method will override any previously defined method of the same name.
An ancestor can be bound by appending as lowercase-ident to the inheritance construct.
lowercase-ident is not a true variable and can only be used to select a method, i.e. in an ex-
pression lowercase-ident # method-name. This gives access to the method method-name as it was
Chapter 9. The OCaml language 173
defined in the parent class even if it is redefined in the current class. The scope of this ancestor
binding is limited to the current class. The ancestor method may be called from a subclass but
only indirectly.
Method definition
A method definition is written method method-name = expr. The definition of a method overrides
any previous definition of this method. The method will be public (that is, not private) if any of
the definition states so.
A private method, method private method-name = expr, is a method that can only be invoked
on self (from other methods of the same object, defined in this class or one of its subclasses).
This invocation is performed using the expression value-name # method-name, where value-name
is directly bound to self at the beginning of the class definition. Private methods do not appear
in object types. A method may have both public and private definitions, but as soon as there is a
public one, all subsequent definitions will be made public.
Methods may have an explicitly polymorphic type, allowing them to be used polymorphically
in programs (even for the same object). The explicit declaration may be done in one of three ways:
(1) by giving an explicit polymorphic type in the method definition, immediately after the method
name, i.e. method [private] method-name : {' ident}+ . typexpr = expr; (2) by a forward
declaration of the explicit polymorphic type through a virtual method definition; (3) by importing
such a declaration through inheritance and/or constraining the type of self.
Some special expressions are available in method bodies for manipulating instance variables and
duplicating self:
expr ::= . . .
| inst-var-name <- expr
| {< [inst-var-name = expr {; inst-var-name = expr} [;]] >}
174
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 1 = expr 1 ; . . . ; inst-var-name n = expr n >} evaluates to a copy
of the current object in which the values of instance variables inst-var-name 1 , . . . , inst-var-name n
have been replaced by the values of the corresponding expressions expr 1 , . . . , expr n .
Explicit overriding
Since Ocaml 3.12, the keywords inherit!, val! and method! have the same semantics as
inherit, val and method, but they additionally require the definition they introduce to be
overriding. Namely, method! requires method-name to be already defined in this class, val!
requires inst-var-name to be already defined in this class, and inherit! requires class-expr to
override some definitions. If no such overriding occurs, an error is signaled.
As a side-effect, these 3 keywords avoid the warnings 7 (method override) and 13 (instance
variable override). Note that warning 7 is disabled by default.
Initializers
A class initializer initializer expr specifies an expression that will be evaluated whenever an
object is created from the class, once all its instance variables have been initialized.
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 9.4).
Virtual class
A class must be flagged virtual if one of its methods is virtual (that is, appears in the class type,
but is not actually defined). Objects cannot be created from a virtual class.
Type parameters
The class type parameters correspond to the ones of the class type and of the two type abbreviations
defined by the class binding. They must be bound to actual types in the class definition using type
constraints. So that the abbreviations are well-formed, type variables of the inferred type of the
class must either be type parameters or be bound in the constraint clause.
This is the counterpart in signatures of class definitions. A class specification matches a class
definition if they have the same type parameters and their types match.
9.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.
An optional ;; is allowed after each specification in a signature. It serves as a syntactic separator
with no semantic meaning.
Chapter 9. The OCaml language 177
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 20).
Type specifications
A specification of one or several type components in a signature is written type typedef {and typedef }
and consists of a sequence of mutually recursive definitions of type names.
Each type definition in the signature specifies an optional type equation = typexpr and an
optional type representation = constr-decl . . . or = { field-decl . . . }. The implementation of the type
name in a matching structure must be compatible with the type expression specified in the equation
(if given), and have the specified representation (if given). Conversely, users of that signature will
be able to rely on the type equation or type representation, if given. More precisely, we have the
following four situations:
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
178
Class specifications
A specification of one or several classes in a signature is written class class-spec {and class-spec}
and consists of a sequence of mutually recursive definitions of class names.
Class specifications are described more precisely in section 9.9.4.
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
instead of
A functor taking two arguments of type S that share their t component is written
Constraints are added left to right. After each constraint has been applied, the resulting signa-
ture must be a subtype of the signature before the constraint was applied. Thus, the with operator
can only add information on the type components of a signature, but never remove information.
180
See also the following language extensions: recursive modules, first-class modules, overriding in
open statements, attributes, extension nodes and generative functors.
9.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 scopes 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.
Chapter 9. The OCaml language 181
For compatibility with toplevel phrases (chapter 12), optional ;; are allowed after and before
each definition in a structure. These ;; have no semantic meanings. Similarly, an expr preceded by
;; is allowed as a component of a structure. It is equivalent to let _ = expr, i.e. expr is evaluated
for its side-effects but is not bound to any identifier. If expr is the first component of a structure,
the preceding ;; can be omitted.
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 9.7.2). 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 20).
Type definitions
A definition of one or several type components is written type typedef {and typedef } and consists
of a sequence of mutually recursive definitions of type names.
Exception definitions
Exceptions are defined with the syntax exception constr-decl or exception constr-name = constr.
Class definitions
A definition of one or several classes is written class class-binding {and class-binding} and consists
of a sequence of mutually recursive definitions of class names. Class definitions are described more
precisely in section 9.9.3.
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
instead of
which is equivalent to
9.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-type 1 , binds module-name to these modules,
evaluates module-expr in the extended environment, and returns the resulting modules as results.
No restrictions are placed on the type of the functor argument; in particular, a functor may take
another functor as argument (“higher-order” functor).
Functor application
The expression module-expr 1 ( module-expr 2 ) evaluates module-expr 1 to a functor and
module-expr 2 to a module, and applies the former to the latter. The type of module-expr 2 must
match the type expected for the arguments of the functor module-expr 1 .
Chapter 9. The OCaml language 183
Compilation units bridge the module system and the separate compilation system. A compila-
tion 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 implementa-
tion contains a sequence of definitions and expressions, 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 con-
taining the interface and the implementation (see chapter 11 for more details). A compilation unit
behaves roughly as the module definition
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
where name 1 . . . name n are the names of the other compilation units available in the search path
(see chapter 11 for more details) and specification1 . . . specificationn are their respective interfaces.
184
Chapter 10
Language extensions
This chapter describes language extensions and convenience features that are implemented in
OCaml, but not described in chapter 9.
which binds name 1 to the cyclic list 1::2::1::2::. . . , and name 2 to the cyclic list
2::1::2::1::. . . Informally, the class of accepted definitions consists of those definitions where
the defined names occur only inside function bodies or as argument to a data constructor.
More precisely, consider the expression:
It will be accepted if each one of expr 1 . . . expr n is statically constructive with respect to
name 1 . . . name n , is not immediately linked to any of name 1 . . . name n , and is not an array
constructor whose arguments have abstract type.
An expression e is said to be statically constructive with respect to the variables name 1 . . . name n
if at least one of the following conditions is true:
• e is a variable
185
186
• e has one of the following forms, where each one of expr 1 . . . expr m is statically construc-
tive with respect to name 1 . . . name n , and expr 0 is statically constructive with respect to
name 1 . . . name n , xname 1 . . . xname m :
An expression e is said to be immediately linked to the variable name in the following cases:
• e is name
• e has the form expr 1 ; . . . ; expr m where expr m is immediately linked to name
• e has the form let [rec] xname 1 = expr 1 and . . . and xname m = expr m in expr 0 where expr 0
is immediately linked to name or to one of the xname i such that expr i is immediately linked
to name.
end = struct
type t = Leaf of string | Node of ASet.t
let compare t1 t2 =
match (t1, t2) with
| (Leaf s1, Leaf s2) -> Stdlib.compare s1 s2
| (Leaf _, Node _) -> 1
| (Node _, Leaf _) -> -1
| (Node n1, Node n2) -> ASet.compare n1 n2
end
and ASet
: Set.S with type elt = A.t
= Set.Make(A)
It can be given the following specification:
module rec A : sig
type t = Leaf of string | Node of ASet.t
val compare: t -> t -> int
end
and ASet : Set.S with type elt = A.t
This is an experimental extension of OCaml: the class of recursive definitions accepted, as well
as its dynamic semantics are not final and subject to change in future releases.
Currently, the compiler requires that all dependency cycles between the recursively-defined
module identifiers go through at least one “safe” module. A module is “safe” if all value definitions
that it contains have function types typexpr 1 -> typexpr 2 . Evaluation of a recursive module
definition proceeds by building initial values for the safe modules involved, binding all (functional)
values to fun _ -> raiseUndefined_recursive_module. The defining module expressions are then
evaluated, and the initial values for the safe modules are replaced by the values thus computed. If a
function component of a safe module is applied during this computation (which corresponds to an
ill-founded recursive definition), the Undefined_recursive_module exception is raised at runtime:
module rec M: sig val f: unit -> int end = struct let f () = N.x end
and N:sig val x: int end = struct let x = M.f () end
Exception:
Undefined_recursive_module ("extensions/recursivemodules.etex", 1, 43).
If there are no safe modules along a dependency cycle, an error is raised
module rec M: sig val x: int end = struct let x = N.y end
and N:sig val x: int val y:int end = struct let x = M.x let y = 0 end
Error : Cannot safely evaluate the definition of the following cycle
of recursively - defined modules : M -> N -> M .
There are no safe modules in this cycle ( see manual section 10.2).
Module M defines an unsafe value , x .
Module N defines an unsafe value , x .
Note that, in the specification case, the module-types must be parenthesized if they use the
with mod-constraint construct.
188
Values of a variant or record type declared private can be de-structured normally in pattern-
matching or via the expr . field notation for record accesses. However, values of these types cannot
be constructed directly by constructor application or record construction. Moreover, assignment
on a mutable field of a private record type is not allowed.
The typical use of private types is in the export signature of a module, to ensure that construc-
tion of values of the private type always go through the functions provided by the module, while
still allowing pattern-matching outside the defining module. For example:
module M : sig
type t = private A | B of int
val a : t
val b : int -> t
end = struct
type t = A | B of int
let a = A
let b n = assert (n > 0); B n
end
Here, the private declaration ensures that in any value of type M.t, the argument to the B con-
structor is always a positive integer.
With respect to the variance of their parameters, private types are handled like abstract types.
That is, if a private type has parameters, their variance is the one explicitly given by prefixing the
parameter by a ‘+’ or a ‘-’, it is invariant otherwise.
Unlike a regular type abbreviation, a private type abbreviation declares a type that is distinct
from its implementation type typexpr. However, coercions from the type to typexpr are permitted.
Moreover, the compiler “knows” the implementation type and can take advantage of this knowledge
to perform type-directed optimizations.
The following example uses a private type abbreviation to define a module of nonnegative
integers:
module N : sig
type t = private int
val of_int: int -> t
val to_int: t -> int
end = struct
type t = int
let of_int n = assert (n >= 0); n
let to_int n = n
end
The type N.t is incompatible with int, ensuring that nonnegative integers and regular integers
are not confused. However, if x has type N.t, the coercion (x :> int) is legal and returns the
underlying integer, just like N.to_int x. Deep coercions are also supported: if l has type N.t list,
the coercion (l :> int list) returns the list of underlying integers, like List.map N.to_int l
but without copying the list l.
Note that the coercion ( expr :> typexpr ) is actually an abbreviated form, and will only
work in presence of private abbreviations if neither the type of expr nor typexpr contain any
type variables. If they do, you must use the full form ( expr : typexpr 1 :> typexpr 2 ) where
typexpr 1 is the expected type of expr. Concretely, this would be (x : N.t :> int) and
(l : N.t list :> int list) for the above examples.
Private row types are type abbreviations where part of the structure of the type is left abstract.
Concretely typexpr in the above should denote either an object type or a polymorphic variant
type, with some possibility of refinement left. If the private declaration is used in an interface, the
corresponding implementation may either provide a ground instance, or a refined private type.
module M : sig type c = private < x : int; .. > val o : c end =
struct
class c = object method x = 3 method y = 2 end
let o = new c
end
This declaration does more than hiding the y method, it also makes the type c incompatible with
any other closed object type, meaning that only o will be of type c. In that respect it behaves
190
similarly to private record types. But private row types are more flexible with respect to incremental
refinement. This feature can be used in combination with functors.
module F(X : sig type c = private < x : int; .. > end) =
struct
let get_x (o : X.c) = o#x
end
module G(X : sig type c = private < x : int; y : int; .. > end) =
struct
include F(X)
let get_y (o : X.c) = o#y
end
A polymorphic variant type [t], for example
type t = [ `A of int | `B of bool ]
can be refined in two ways. A definition [u] may add new field to [t], and the declaration
type u = private [> t]
will keep those new fields abstract. Construction of values of type [u] is possible using the known
variants of [t], but any pattern-matching will require a default case to handle the potential extra
fields. Dually, a declaration [u] may restrict the fields of [t] through abstraction: the declaration
type v = private [< t > `A]
corresponds to private variant types. One cannot create a value of the private type [v], except
using the constructors that are explicitly listed as present, (`A n) in this example; yet, when
patter-matching on a [v], one should assume that any of the constructors of [t] could be present.
Similarly to abstract types, the variance of type parameters is not inferred, and must be given
explicitly.
The expression fun ( type typeconstr-name ) -> expr introduces a type constructor named
typeconstr-name which is considered abstract in the scope of the sub-expression, but then replaced
by a fresh type variable. Note that contrary to what the syntax could suggest, the expression
fun ( type typeconstr-name ) -> expr itself does not suspend the evaluation of expr as a regular
abstraction would. The syntax has been chosen to fit nicely in the context of function declarations,
where it is generally used. It is possible to freely mix regular function parameters with pseudo type
parameters, as in:
let f = fun (type t) (foo : t list) -> ...
and even use the alternative syntax for declaring functions:
let f (type t) (foo : t list) = ...
Chapter 10. Language extensions 191
If several locally abstract types need to be introduced, it is possible to use the syn-
tax fun ( type typeconstr-name 1 . . . typeconstr-name n ) -> expr as syntactic sugar for
fun ( type typeconstr-name 1 ) -> . . . -> fun ( type typeconstr-name n ) -> expr. For instance,
let f = fun (type t u v) -> fun (foo : (t * u * v) list) -> ...
let f' (type t u v) (foo : (t * u * v) list) = ...
This construction is useful because the type constructors it introduces can be used in places
where a type variable is not allowed. For instance, one can use it to define an exception in a local
module within a polymorphic function.
let f (type t) () =
let module M = struct exception E of t end in
(fun x -> M.E x), (function M.E x -> Some x | _ -> None)
Here is another example:
let sort_uniq (type s) (cmp : s -> s -> int) =
let module S = Set.Make(struct type t = s let compare = cmp end) in
fun l ->
S.elements (List.fold_right S.add l S.empty)
It is also extremely useful for first-class modules (see section 10.5) and generalized algebraic
datatypes (GADTs: see section 10.10).
The (type typeconstr-name ) syntax construction by itself does not make polymorphic the
type variable it introduces, but it can be combined with explicit polymorphic annotations where
needed. The above rule is provided as syntactic sugar to make this easier:
let rec f : type t1 t2. t1 * t2 list -> t1 = ...
is automatically expanded into
let rec f : 't1 't2. 't1 * 't2 list -> 't1 =
fun (type t1) (type t2) -> ( ... : t1 * t2 list -> t1)
This syntax can be very useful when defining recursive functions involving GADTs, see the sec-
tion 10.10 for a more detailed explanation.
The same feature is provided for method definitions.
Modules are typically thought of as static components. This extension makes it possible to pack
a module as a first-class value, which can later be dynamically unpacked into a module.
The expression ( module module-expr : package-type ) converts the module (structure or func-
tor) denoted by module expression module-expr to a value of the core language that encapsulates
this module. The type of this core language value is ( module package-type ). The package-type
annotation can be omitted if it can be inferred from the context.
Conversely, the module expression ( val expr : package-type ) evaluates the core language
expression expr to a value, which must have type module package-type, and extracts the module
that was encapsulated in this value. Again package-type can be omitted if the type of expr is
known. If the module expression is already parenthesized, like the arguments of functors are, no
additional parens are needed: Map.Make(val key).
The pattern ( module module-name : package-type ) matches a package with type
package-type and binds it to module-name. It is not allowed in toplevel let bindings. Again
package-type can be omitted if it can be inferred from the enclosing pattern.
The package-type syntactic class appearing in the ( module package-type ) type expression and
in the annotated forms represents a subset of module types. This subset consists of named module
types with optional constraints of a limited form: only non-parametrized types can be specified.
For type-checking purposes (and starting from OCaml 4.02), package types are compared using
the structural comparison of module types.
In general, the module expression ( val expr : package-type ) cannot be used in the body of
a functor, because this could cause unsoundness in conjunction with applicative functors. Since
OCaml 4.02, this is relaxed in two ways: if package-type does not contain nominal type declarations
(i.e. types that are created with a proper identity), then this expression can be used anywhere,
and even if it contains such types it can be used inside the body of a generative functor, de-
scribed in section 10.15. It can also be used anywhere in the context of a local module binding
let module module-name = ( val expr 1 : package-type ) in expr 2 .
Chapter 10. Language extensions 193
Basic example A typical use of first-class modules is to select at run-time among several
implementations of a signature. Each implementation is a structure that we can encapsulate as a
first-class module, then store in a data structure such as a hash table:
type picture = ...
module type DEVICE = sig
val draw : picture -> unit
...
end
let devices : (string, (module DEVICE)) Hashtbl.t = Hashtbl.create 17
Advanced examples With first-class modules, it is possible to parametrize some code over the
implementation of a module without using a functor.
let sort (type s) (module Set : Set.S with type elt = s) l =
Set.elements (List.fold_right Set.add l Set.empty)
val sort : (module Set.S with type elt = 's) -> 's list -> 's list = <fun>
To use this function, one can wrap the Set.Make functor:
let make_set (type s) cmp =
let module S = Set.Make(struct
type t = s
let compare = cmp
end) in
(module S : Set.S with type elt = s)
194
val make_set : ('s -> 's -> int) -> (module Set.S with type elt = 's) = <fun>
The construction module type of module-expr expands to the module type (signature or functor
type) inferred for the module expression module-expr. To make this module type reusable in many
situations, it is intentionally not strengthened: abstract types and datatypes are not explicitly
related with the types of the original module. For the same reason, module aliases in the inferred
type are expanded.
A typical use, in conjunction with the signature-level include construct, is to extend the
signature of an existing structure. In that case, one wants to keep the types equal to types in the
original module. This can done using the following idiom.
module type MYHASH = sig
include module type of struct include Hashtbl end
val replace: ('a, 'b) t -> 'a -> 'b -> unit
end
The signature MYHASH then contains all the fields of the signature of the module Hashtbl (with
strengthened type definitions), plus the new field replace. An implementation of this signature can
be obtained easily by using the include construct again, but this time at the structure level:
module MyHash : MYHASH = struct
include Hashtbl
let replace t k v = remove t k; add t k v
end
Another application where the absence of strengthening comes handy, is to provide an alterna-
tive implementation for an existing module.
module MySet : module type of Set = struct
...
end
This idiom guarantees that Myset is compatible with Set, but allows it to represent sets internally
in a different way.
A “destructive” substitution (with... :=...) behaves essentially like normal signature constraints
(with... =...), but it additionally removes the redefined type or module from the signature.
Prior to OCaml 4.06, there were a number of restrictions: one could only remove types and
modules at the outermost level (not inside submodules), and in the case of with␣type the definition
had to be another type constructor with the same type parameters.
A natural application of destructive substitution is merging two signatures sharing a type
name.
module type Printable = sig
type t
val print : Format.formatter -> t -> unit
end
module type Comparable = sig
type t
val compare : t -> t -> int
end
module type PrintableComparable = sig
include Printable
include Comparable with type t := t
end
One can also use this to completely remove a field:
module type S = Comparable with type t := int
module type S = sig val compare : int -> int -> int end
or to rename one:
module type S = sig
type u
include Comparable with type t := u
end
module type S = sig type u val compare : u -> u -> int end
Note that you can also remove manifest types, by substituting with the same type.
module type ComparableInt = Comparable with type t = int ;;
module type ComparableInt = sig type t = int val compare : t -> t -> int end
Local substitutions behave like destructive substitutions (with... :=...) but instead of being
applied to a whole signature after the fact, they are introduced during the specification of the
signature, and will apply to all the items that follow.
This provides a convenient way to introduce local names for types and modules when defining
a signature:
module type S = sig
type t
module Sub : sig
type outer := t
type t
val to_outer : t -> outer
end
end
module type S =
sig type t module Sub : sig type t val to_outer : t/1 -> t/2 end end
Note that, unlike type declarations, type substitution declarations are not recursive, so substi-
tutions like the following are rejected:
# module type S = sig
type 'a poly_list := [ `Cons of 'a * 'a poly_list | `Nil ]
end ;;
Error : Unbound type constructor poly_list
Module type substitution essentially behaves like type substitutions. They are useful to refine
an abstract module type in a signature into a concrete module type,
# module type ENDO = sig
module type T
module F: T -> T
Chapter 10. Language extensions 197
end
module Endo(X: sig module type T end): ENDO with module type T = X.T =
struct
module type T = X.T
module F(X:T) = X
end;;
module type ENDO = sig module type T module F : T -> T end
module Endo :
functor (X : sig module type T end) ->
sig module type T = X.T module F : T -> T end
It is also possible to substitute a concrete module type with an equivalent module types.
module type A = sig
type x
module type R = sig
type a = A of x
type b
end
end
module type S = sig
type a = A of int
type b
end
module type B = A with type x = int and module type R = S
However, such substitutions are never necessary.
Destructive module type substitution removes the module type substitution from the signa-
ture
# module type ENDO' = ENDO with module type T := ENDO;;
module type ENDO' = sig module F : ENDO -> ENDO end
If the right hand side of the substitution is not a path, then the destructive substitution is only
valid if the left-hand side of the substitution is never used as the type of a first-class module in the
original module type.
module type T = sig module type S val x: (module S) end
module type Error = T with module type S := sig end
Error : This ` with ' constraint S := sig end makes a packed module ill - formed .
The above specification, inside a signature, only matches a module definition equal to
module-path. Conversely, a type-level module alias can be matched by itself, or by any supertype
of the type of the module it references.
There are several restrictions on module-path:
2. inside the body of a functor, M0 should not be one of the functor parameters;
3. inside a recursive module definition, M0 should not be one of the recursively defined modules.
Such specifications are also inferred. Namely, when P is a path satisfying the above con-
straints,
module N = P
has type
module N = P
Type-level module aliases are used when checking module path equalities. That is, in a context
where module name N is known to be an alias for P, not only these two module paths check as
equal, but F (N ) and F (P) are also recognized as equal. In the default compilation mode, this is
the only difference with the previous approach of module aliases having just the same module type
as the module they reference.
When the compiler flag -no-alias-deps is enabled, type-level module aliases are also exploited
to avoid introducing dependencies between compilation units. Namely, a module alias referring
to a module inside another compilation unit does not introduce a link-time dependency on that
compilation unit, as long as it is not dereferenced; it still introduces a compile-time dependency
if the interface needs to be read, i.e. if the module is a submodule of the compilation unit, or if
some type components are referred to. Additionally, accessing a module alias introduces a link-time
dependency on the compilation unit containing the module referenced by the alias, rather than the
compilation unit containing the alias. Note that these differences in link-time behavior may be
incompatible with the previous behavior, as some compilation units might not be extracted from
libraries, and their side-effects ignored.
These weakened dependencies make possible to use module aliases in place of the -pack mech-
anism. Suppose that you have a library Mylib composed of modules A and B. Using -pack, one
would issue the command line
and as a result obtain a Mylib compilation unit, containing physically A and B as submodules,
and with no dependencies on their respective compilation units. Here is a concrete example of a
possible alternative approach:
module A = Mylib__A
module B = Mylib__B
Chapter 10. Language extensions 199
3. Compile Mylib.ml using -no-alias-deps, and the other files using -no-alias-deps and
-open Mylib (the last one is equivalent to adding the line open! Mylib at the top of each
file).
4. Finally, create a library containing all the compilation units, and export all the compiled
interfaces.
This approach lets you access A and B directly inside the library, and as Mylib.A and Mylib.B from
outside. It also has the advantage that Mylib is no longer monolithic: if you use Mylib.A, only
Mylib__A will be linked in, not Mylib__B.
Note the use of double underscores in Mylib__A and Mylib__B. These were chosen on pur-
pose; the compiler uses the following heuristic when printing paths: given a path Lib__fooBar,
if Lib.FooBar exists and is an alias for Lib__fooBar, then the compiler will always display
Lib.FooBar instead of Lib__fooBar. This way the long Mylib__ names stay hidden and all the
user sees is the nicer dot names. This is how the OCaml standard library is compiled.
Since OCaml 4.01, open statements shadowing an existing identifier (which is later used) trigger
the warning 44. Adding a ! character after the open keyword indicates that such a shadowing is
intentional and should not trigger the warning.
This is also available (since OCaml 4.06) for local opens in class expressions and class type
expressions.
200
This extension provides syntactic sugar for getting and setting elements in the arrays provided
by the Bigarray[25.5] module.
The short expressions are translated into calls to functions of the Bigarray module as described
in the following table.
expression translation
expr 0 .{ expr 1 } Bigarray.Array1.get expr 0 expr 1
expr 0 .{ expr 1 } <- expr Bigarray.Array1.set expr 0 expr 1 expr
expr 0 .{ expr 1 , expr 2 } Bigarray.Array2.get expr 0 expr 1 expr 2
expr 0 .{ expr 1 , expr 2 } <- expr Bigarray.Array2.set expr 0 expr 1 expr 2 expr
expr 0 .{ expr 1 , expr 2 , expr 3 } Bigarray.Array3.get expr 0 expr 1 expr 2 expr 3
expr 0 .{ expr 1 , expr 2 , expr 3 } <- expr Bigarray.Array3.set expr 0 expr 1 expr 2 expr 3 expr
expr 0 .{ expr 1 , . . . , expr n } Bigarray.Genarray.get expr 0 [| expr 1 , . . . , expr n |]
expr 0 .{ expr 1 , . . . , expr n } <- expr Bigarray.Genarray.set expr 0 [| expr 1 , . . . , expr n |] expr
Chapter 10. Language extensions 201
10.12 Attributes
(Introduced in OCaml 4.02, infix notations for constructs other than expressions added in 4.03)
Attributes are “decorations” of the syntax tree which are mostly ignored by the type-checker
but can be used by external tools. An attribute is made of an identifier and a payload, which
can be a structure, a type expression (prefixed with :), a signature (prefixed with :) or a pattern
(prefixed with ?) optionally followed by a when clause:
The first form of attributes is attached with a postfix notation on “algebraic” categories:
This form of attributes can also be inserted after the ` tag-name in polymorphic variant type
expressions (tag-spec-first, tag-spec, tag-spec-full) or after the method-name in method-type.
The same syntactic form is also used to attach attributes to labels and constructors in type
declarations:
202
Note: when a label declaration is followed by a semi-colon, attributes can also be put after the
semi-colon (in which case they are merged to those specified before).
The second form of attributes are attached to “blocks” such as type declarations, class fields,
etc:
Chapter 10. Language extensions 203
A third form of attributes appears as stand-alone structure or signature items in the module or
class sub-languages. They are not attached to any specific node in the syntax tree:
(Note: contrary to what the grammar above describes, item-attributes cannot be attached to
these floating attributes in class-field-spec and class-field.)
It is also possible to specify attributes using an infix syntax. For instance:
• “ocaml.warning” or “warning”, with a string literal payload. This can be used as floating
attributes in a signature/structure/object/object type. The string is parsed and has the
same effect as the -w command-line option, in the scope between the attribute and the end
of the current signature/structure/object/object type. The attribute can also be attached
to any kind of syntactic item which support attributes (such as an expression, or a type
expression) in which case its scope is limited to that item. Note that it is not well-defined
which scope is used for a specific warning. This is implementation dependent and can change
between versions. Some warnings are even completely outside the control of “ocaml.warning”
(for instance, warnings 1, 2, 14, 29 and 50).
Chapter 10. Language extensions 205
• “ocaml.deprecated” or “deprecated”: alias for the “deprecated” alert, see section 10.21.
• “ocaml.ppwarning” or “ppwarning”, in any context, with a string literal payload. The text
is reported as warning (22) by the compiler (currently, the warning location is the location
of the string payload). This is mostly useful for preprocessors which need to communicate
warnings to the user. This could also be used to mark explicitly some code location for further
inspection.
• “ocaml.tailcall” or “tailcall” can be applied to function application in order to check that the
call is tailcall optimized. If it it not the case, a warning (51) is emitted.
• ocaml.unboxed or unboxed can be used on a type definition if the type is a single-field record
or a concrete type with a single constructor that has a single argument. It tells the compiler
to optimize the representation of the type by removing the block that represents the record
or the constructor (i.e. a value of this type is physically equal to its argument). In the case of
GADTs, an additional restriction applies: the argument must not be an existential variable,
represented by an existential type variable, or an abstract type constructor applied to an
existential type variable.
• ocaml.local or local take either never, always, maybe or nothing as payload on a func-
tion definition. If no payload is provided, the default is always. The attribute controls an
optimization which consists in compiling a function into a static continuation. Contrary to
inlining, this optimization does not duplicate the function’s body. This is possible when all
references to the function are full applications, all sharing the same continuation (for instance,
the returned value of several branches of a pattern matching). never disables the optimiza-
tion, always asserts that the optimization applies (otherwise a warning 55 is emitted) and
maybe lets the optimization apply when possible (this is the default behavior when the at-
tribute is not specified). The optimization is implicitly disabled when using the bytecode
compiler in debug mode (-g), and for functions marked with an ocaml.inline always or
ocaml.unrolled attribute which supersede ocaml.local.
module X = struct
[@@@warning "+9"] (∗ locally enable warning 9 in this structure ∗)
...
end
[@@deprecated "Please use module 'Y' instead."]
type t = A | B
[@@deprecated "Please use type 's' instead."]
let fires_warning_22 x =
assert (x >= 0) [@ppwarning "TODO: remove this later"]
Warning 22 [ preprocessor ]: TODO : remove this later
let f x = x [@@inline]
let () = (f[@inlined]) ()
type fragile =
| Int of int [@warn_on_literal_pattern]
| String of string [@warn_on_literal_pattern]
let fragile_match_1 = function
| Int 0 -> ()
| _ -> ()
Warning 52 [ fragile - literal - pattern ]: Code should not depend on the actual values of
this constructor ' s arguments . They are only for information
and may change in future versions . ( See manual section 11.5)
val fragile_match_1 : fragile -> unit = <fun >
include Sys.Immediate64.Make(Int)(Int64)
end
A second form of extension node can be used in structures and signatures, both in the module
and object languages:
Chapter 10. Language extensions 209
An infix form is available for extension nodes when the payload is of the same kind (expression
with expression, pattern with pattern ...).
Examples:
When this form is used together with the infix syntax for attributes, the attributes are considered
to apply to the payload:
An additional shorthand let%foo x in ... is available for convenience when extension nodes
are used to implement binding operators (See 10.23.1).
Furthermore, quoted strings {|...|} can be combined with extension nodes to embed foreign
syntax fragments. Those fragments can be interpreted by a preprocessor and turned into OCaml
code without requiring escaping quotes. A syntax shortcut is available for them:
For instance, you can use {%sql|...|} to represent arbitrary SQL statements – assuming you
have a ppx-rewriter that recognizes the %sql extension.
Note that the word-delimited form, for example {sql|...|sql}, should not be used for signaling
that an extension is in use. Indeed, the user cannot see from the code whether this string literal
has different semantics than they expect. Moreover, giving semantics to a specific delimiter limits
the freedom to change the delimiter to avoid escaping issues.
210
type t = ..
type t += X of int | Y of string
let x = [%extension_constructor X]
let y = [%extension_constructor Y]
# x <> y;;
- : bool = true
Extensible variant types are variant types which can be extended with new variant constructors.
Extensible variant types are defined using ... New variant constructors are added using +=.
module Expr = struct
type attr = ..
type attr +=
| Int of int
| Float of float
end
Chapter 10. Language extensions 211
Pattern matching on an extensible variant type requires a default case to handle unknown
variant constructors:
let to_string = function
| Expr.Str s -> s
| Expr.Int i -> Int.to_string i
| Expr.Float f -> string_of_float f
| _ -> "?"
A preexisting example of an extensible variant type is the built-in exn type used for exceptions.
Indeed, exception constructors can be declared using the type extension syntax:
type exn += Exc of int
Extensible variant constructors can be rebound to a different name. This allows exporting
variants from another module.
# let not_in_scope = Str "Foo";;
Error : Unbound constructor Str
Extensible variant types can be declared private. This prevents new constructors from being
declared directly, but allows extension constructors to be referred to in interfaces.
module Msg : sig
type t = private ..
module MkConstr (X : sig type t end) : sig
type t += C of X.t
end
end = struct
type t = ..
module MkConstr (X : sig type t end) = struct
type t += C of X.t
end
end
A generative functor takes a unit () argument. In order to use it, one must necessarily apply
it to this unit argument, ensuring that all type components in the result of the functor behave
in a generative way, i.e. they are different from types obtained by other applications of the same
functor. This is equivalent to taking an argument of signature sig end, and always applying to
struct end, but not to some defined module (in the latter case, applying twice to the same module
would return identical types).
As a side-effect of this generativity, one is allowed to unpack first-class modules in the body of
generative functors.
Chapter 10. Language extensions 213
There are two classes of operators available for extensions: infix operators with a name starting
with a # character and containing more than one # character, and unary operators with a name
(starting with a ?, ~, or ! character) containing at least one # character.
For instance:
# let infix x y = x##y;;
Error : '## ' is not a valid value identifier .
Int and float literals followed by an one-letter identifier in the range [g.. z | G.. Z] are extension-only
literals.
214
The arguments of sum-type constructors can now be defined using the same syntax as records.
Mutable and polymorphic fields are allowed. GADT syntax is supported. Attributes can be
specified on individual fields.
Syntactically, building or matching constructors with such an inline record argument is similar
to working with a unary constructor whose unique argument is a declared record type. A pattern
can bind the inline record as a pseudo-value, but the record cannot escape the scope of the binding
and can only be used with the dot-notation to extract or modify fields or to build new constructor
values.
type t =
| Point of {width: int; mutable x: float; mutable y: float}
| Other
Comments which start with ** are also used by the ocamldoc documentation generator (see
17). The three comment forms recognised by the compiler are a subset of the forms accepted by
ocamldoc (see 17.2).
let mkT = T
will be converted to:
type t = T
let mkT = T
type t2 = {
fld: int; (∗∗ Record field ∗)
fld2: float;
}
type t3 =
| Cstr of string (∗∗ Variant constructor ∗)
| Cstr2 of string
type t5 = [
`PCstr (∗∗ Polymorphic variant constructor ∗)
]
will be converted to:
type t1 = lbl:(int [@ocaml.doc " Labelled argument "]) -> unit
type t2 = {
fld: int [@ocaml.doc " Record field "];
fld2: float;
}
type t3 =
| Cstr of string [@ocaml.doc " Variant constructor "]
| Cstr2 of string
type t4 = < meth : int * int [@ocaml.doc " Object method "] >
type t5 = [
`PCstr [@ocaml.doc " Polymorphic variant constructor "]
]
Note that label comments take precedence over item comments, so:
type t = T of string
(∗∗ Attaches to T not t ∗)
will be converted to:
type t = T of string [@ocaml.doc " Attaches to T not t "]
Chapter 10. Language extensions 217
whilst:
type t = T of string
(∗∗ Attaches to T not t ∗)
(∗∗ Attaches to t ∗)
will be converted to:
type t = T of string [@ocaml.doc " Attaches to T not t "]
[@@ocaml.doc " Attaches to t "]
In the absence of meaningful comment on the last constructor of a type, an empty comment (**)
can be used instead:
type t = T of string
(∗∗)
(∗∗ Attaches to t ∗)
will be converted directly to
type t = T of string
[@@ocaml.doc " Attaches to t "]
dot-ext ::=
| dot-operator-char {operator-char}
dot-operator-char ::= ! | ? | core-operator-char | % | :
expr ::= ...
| expr . [module-path .] dot-ext (( expr ) | [ expr ] | { expr }) [<- expr]
operator-name ::= ...
| . dot-ext (() | [] | {}) [<-]
This extension provides syntactic sugar for getting and setting elements for user-defined indexed
types. For instance, we can define python-like dictionaries with
module Dict = struct
include Hashtbl
let ( .%{} ) tabl index = find tabl index
let ( .%{}<- ) tabl index value = add tabl index value
end
let dict =
let dict = Dict.create 10 in
let () =
dict.Dict.%{"one"} <- 1;
218
10.21 Alerts
(Introduced in 4.08)
Since OCaml 4.08, it is possible to mark components (such as value or type declarations)
in signatures with “alerts” that will be reported when those components are referenced. This
generalizes the notion of “deprecated” components which were previously reported as warning 3.
Those alerts can be used for instance to report usage of unsafe features, or of features which are
only available on some platforms, etc.
Alert categories are identified by a symbolic identifier (a lowercase identifier, following the usual
lexical rules) and an optional message. The identifier is used to control which alerts are enabled,
and which ones are turned into fatal errors. The message is reported to the user when the alert is
triggered (i.e. when the marked component is referenced).
The ocaml.alert or alert attribute serves two purposes: (i) to mark component with an
alert to be triggered when the component is referenced, and (ii) to control which alert names are
enabled. In the first form, the attribute takes an identifier possibly followed by a message. Here is
an example of a value declaration marked with an alert:
module U: sig
val fork: unit -> bool
[@@alert unix "This function is only available under Unix."]
end
220
Here unix is the identifier for the alert. If this alert category is enabled, any reference to U.fork
will produce a message at compile time, which can be turned or not into a fatal error.
And here is another example as a floating attribute on top of an “.mli” file (i.e. before any other
non-attribute item) or on top of an “.ml” file without a corresponding interface file, so that any
reference to that unit will trigger the alert:
Controlling which alerts are enabled and whether they are turned into fatal errors is done either
through the compiler’s command-line option -alert <spec> or locally in the code through the
alert or ocaml.alert attribute taking a single string payload <spec>. In both cases, the syntax
for <spec> is a concatenation of items of the form:
(* Disable all alerts, reenables just unix (as a soft alert) and window
(as a fatal-error), for the rest of the current structure *)
[@@@alert "-all--all+unix@window"]
...
let x =
(* Locally disable the window alert *)
begin[@alert "-window"]
...
end
Before OCaml 4.08, there was support for a single kind of deprecation alert. It is now known
as the deprecated alert, but legacy attributes to trigger it and the legacy ways to control it as
warning 3 are still supported. For instance, passing -w +3 on the command-line is equivant to
-alert +deprecated, and:
val x: int
[@@@ocaml.deprecated "Please do something else"]
is equivalent to:
val x: int
[@@@ocaml.alert deprecated "Please do something else"]
Chapter 10. Language extensions 221
This extension makes it possible to open any module expression in module structures and
expressions. A similar mechanism is also available inside module types, but only for extended
module paths (e.g. F(X).G(Y)).
For instance, a module can be constrained when opened with
module M = struct let x = 0 let hidden = 1 end
open (M:sig val x: int end)
let y = hidden
Error : Unbound value hidden
Another possibility is to immediately open the result of a functor application
let sort (type x) (x:x list) =
let open Set.Make(struct type t = x let compare=compare end) in
elements (of_list x)
val sort : 'x list -> 'x list = <fun>
Going further, this construction can introduce local components inside a structure,
module M = struct
let x = 0
open! struct
let x = 0
let y = 1
end
let w = x + y
end
module M : sig val x : int val w : int end
One important restriction is that types introduced by open struct... end cannot appear in the
signature of the enclosing structure, unless they are defined equal to some non-local type. So:
222
module M = struct
open struct type 'a t = 'a option = None | Some of 'a end
let x : int t = Some 1
end
module M : sig val x : int option end
is OK, but:
module M = struct
open struct type t = A end
let x = A
end
Error : The type t /556 introduced by this open appears in the signature
File " extensions / generalizedopens . etex " , line 3 , characters 6 -7:
The value x has no valid type if t /556 is hidden
is not because x cannot be given any type other than t, which only exists locally. Although the
above would be OK if x too was local:
module M: sig end = struct
open struct
type t = A
end
...
open struct let x = A end
...
end
module M : sig end
Inside signatures, extended opens are limited to extended module paths,
module type S = sig
module F: sig end -> sig type t end
module X: sig end
open F(X)
val f: t
end
module type S =
sig
module F : sig end -> sig type t end
module X : sig end
val f : F(X).t
end
and not
class c =
let open Set.Make(Int) in
...
let-operator ::=
| let (core-operator-char | <) {dot-operator-char}
and-operator ::=
| and (core-operator-char | <) {dot-operator-char}
operator-name ::= ...
| let-operator
| and-operator
letop-binding ::= pattern = expr
| value-name
expr ::= ...
| let-operator letop-binding {and-operator letop-binding} in expr
open Seq
end
module ZipSeq :
sig
type 'a t = 'a Seq.t
val return : 'a -> 'a Seq.t
val prod : 'a Seq.t -> 'b Seq.t -> ('a * 'b) Seq.t
val ( let+ ) : 'a Seq.t -> ('a -> 'b) -> 'b Seq.t
val ( and+ ) : 'a Seq.t -> 'b Seq.t -> ('a * 'b) Seq.t
end
to support the syntax:
open ZipSeq
let sum3 z1 z2 z3 =
let+ x1 = z1
and+ x2 = z2
and+ x3 = z3 in
x1 + x2 + x3
val sum3 : int Seq.t -> int Seq.t -> int Seq.t -> int Seq.t = <fun>
which is equivalent to this expanded form:
open ZipSeq
let sum3 z1 z2 z3 =
( let+ ) (( and+ ) (( and+ ) z1 z2) z3)
(fun ((x1, x2), x3) -> x1 + x2 + x3)
Chapter 10. Language extensions 225
val sum3 : int Seq.t -> int Seq.t -> int Seq.t -> int Seq.t = <fun>
10.23.2 Rationale
This extension is intended to provide a convenient syntax for working with monads and applicatives.
An applicative should provide a module implementing the following interface:
module type Applicative_syntax = sig
type 'a t
val ( let+ ) : 'a t -> ('a -> 'b) -> 'b t
val ( and+ ): 'a t -> 'b t -> ('a * 'b) t
end
where (let+) is bound to the map operation and (and+) is bound to the monoidal product
operation.
A monad should provide a module implementing the following interface:
module type Monad_syntax = sig
include Applicative_syntax
val ( let* ) : 'a t -> ('a -> 'b t) -> 'b t
val ( and* ): 'a t -> 'b t -> ('a * 'b) t
end
where (let*) is bound to the bind operation, and (and*) is also bound to the monoidal product
operation.
226
Part III
227
Chapter 11
This chapter describes the OCaml batch compiler ocamlc, which compiles OCaml source files to
bytecode object files and links these object files to produce standalone bytecode executable files.
These executable files are then run by the bytecode interpreter ocamlrun.
• Arguments ending in .mli are taken to be source files for compilation unit interfaces. Inter-
faces 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
OCaml 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.
229
230
• 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 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 (.obj
under Windows). This object file is linked with the program if the -custom flag is set (see
the description of -custom below).
• Arguments ending in .so (.dll under Windows) are assumed to be C shared libraries (DLLs).
During linking, they are searched for external C functions referenced from the OCaml code,
and their names are written in the generated bytecode executable. The run-time system
ocamlrun then loads them dynamically at program start-up time.
The output of the linking phase is a file containing compiled bytecode that can be executed by
the OCaml bytecode interpreter: the command named ocamlrun. If a.out is the name of the file
produced by the linking phase, the command
executes the compiled code contained in a.out, passing it as arguments the character strings
arg 1 to arg n . (See chapter 13 for more details.)
On most systems, the file produced by the linking phase can be run directly, as in:
The produced file has the executable bit set, and it manages to launch the bytecode interpreter
by itself.
The compiler is able to emit some information on its internal stages. It can output .cmt files
for the implementation of the compilation unit and .cmti for signatures if the option -bin-annot
is passed to it (see the description of -bin-annot below). Each such file contains a typed abstract
syntax tree (AST), that is produced during the type checking procedure. This tree contains all
available information about the location and the specific type of each term in the source file. The
AST is partial if type checking was unsuccessful.
These .cmt and .cmti files are typically useful for code inspection tools.
11.2 Options
The following command-line options are recognized by ocamlc. The options -pack, -a, -c,
-output-obj and -output-complete-obj are mutually exclusive.
Chapter 11. Batch compilation (ocamlc) 231
-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 must be set with the -o option.
If -custom, -cclib or -ccopt options are passed on the command line, these options are
stored in the resulting .cmalibrary. Then, linking with this library automatically adds back
the -custom, -cclib and -ccopt options as if they had been provided on the command line,
unless the -noautolink option is given.
-absname
Force error messages to show absolute paths for file names.
-annot
Deprecated since OCaml 4.11. Please use -bin-annot instead.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-bin-annot
Dump detailed information about the compilation (types, bindings, tail-calls, etc) in bi-
nary format. The information for file src.ml (resp. src.mli) is put into file src.cmt (resp.
src.cmti). In case of a type error, dump all the information inferred by the type-checker be-
fore the error. The *.cmt and *.cmti files produced by -bin-annot contain more information
and are much more compact than the files produced by -annot.
-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.
-cc ccomp
Use ccomp as the C linker when linking in “custom runtime” mode (see the -custom option)
and as the C compiler for compiling .c source files.
-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,
for instance-ccopt -Ldir causes the C linker to search for C libraries in directory dir.(See
the -custom option.)
-color mode
Enable or disable colors in compiler messages (especially warnings and errors). The following
modes are supported:
auto
use heuristics to enable colors only if the output supports them (an ANSI-compatible
tty terminal);
232
always
enable colors unconditionally;
never
disable color output.
The default setting is ’auto’, and the current heuristic checks that the TERM environment
variable exists and is not empty or dumb, and that ’isatty(stderr)’ holds.
The environment variable OCAML_COLOR is considered if -color is not provided. Its values
are auto/always/never as above.
-error-style mode
Control the way error messages and warnings are printed. The following modes are supported:
short
only print the error and its location;
contextual
like short, but also display the source code snippet corresponding to the location of the
error.
-compat-32
Check that the generated bytecode executable can run on 32-bit platforms and signal an error
if it cannot. This is useful when compiling bytecode on a 64-bit machine.
-config
Print the version number of ocamlc and a detailed summary of its configuration, then exit.
-config-var var
Print the value of a specific configuration variable from the -config output, then exit. If the
variable does not exist, the exit code is non-zero. This option is only available since OCaml
4.08, so script authors should have a fallback for older versions.
-custom
Link in “custom runtime” mode. In the default linking mode, the linker 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
static linking of OCaml code with user-defined C functions, as described in chapter 20.
Unix:
Unix:
Security warning: never set the “setuid” or “setgid” bits on executables pro-
duced by ocamlc -custom, this would make them vulnerable to attacks.
-depend ocamldep-args
Compute dependencies, as the ocamldep command would do. The remaining arguments are
interpreted as if they were given to the ocamldep command.
-dllib -llibname
Arrange for the C shared library dlllibname.so (dlllibname.dll under Windows) to be
loaded dynamically by the run-time system ocamlrun at program start-up time.
-dllpath dir
Adds the directory dir to the run-time search path for shared C libraries. At link-time, shared
libraries are searched in the standard search path (the one corresponding to the -I option).
The -dllpath option simply stores dir in the produced executable file, where ocamlrun can
find it and use it as described in section 13.3.
-for-pack module-path
Generate an object file (.cmo) that can later be included as a sub-module (with the given
access path) of a compilation unit constructed with -pack. For instance, ocamlc -for-pack P
-c A.ml will generate a..cmo that can later be used with ocamlc -pack -o P.cmo a.cmo. Note:
you can still pack a module that was compiled without -for-pack but in this case exceptions
will be printed with the wrong names.
-g Add debugging information while compiling and linking. This option is required in order
to be able to debug the program with ocamldebug (see chapter 18), and to produce stack
backtraces when the program terminates on an uncaught exception (see section 13.2).
-i Cause the compiler to print all defined names (with their inferred types or their definitions)
when compiling an implementation (.ml file). No compiled files (.cmo and .cmi files) are
produced. 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),
compiled object code files .cmo, libraries (.cma) and C libraries specified with -cclib -lxxx.
By default, the current directory is searched first, then the standard library directory. Di-
rectories 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. See also option
-nostdlib.
If the given directory starts with +, it is taken relative to the standard library directory. For
instance, -I +unix adds the subdirectory unix of the standard library to the search path.
234
-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.
-intf-suffix string
Recognize file names ending with string as interface files (instead of the default .mli).
-labels
Labels are not ignored in types, labels may be used in applications, and labelled parameters
can be given in any order. This is the default.
-linkall
Force 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 (option -a), setting the -linkall option
forces all subsequent links of programs involving that library to link all the modules contained
in the library. When compiling a module (option -c), setting the -linkall option ensures
that this module will always be linked if it is put in a library and this library is linked.
-make-runtime
Build a custom runtime system (in the file specified by option -o) incorporating the C object
files and libraries given on the command line. This custom runtime system can be used later
to execute bytecode executables produced with the ocamlc -use-runtime runtime-name
option. See section 20.1.6 for more information.
-match-context-rows
Set the number of rows of context used for optimization during pattern matching compilation.
The default value is 32. Lower values cause faster compilation, but less optimized code. This
advanced option is meant for use in the event that a pattern-match-heavy program leads to
significant increases in compilation time.
-no-alias-deps
Do not record dependencies for module aliases. See section 10.8 for more information.
-no-app-funct
Deactivates the applicative behaviour of functors. With this option, each functor application
generates new types in its result and applying the same functor twice to the same argument
yields two incompatible structures.
-noassert
Do not compile assertion checks. Note that the special form assert false is always compiled
because it is typed specially. This flag has no effect when linking already-compiled files.
-noautolink
When linking .cmalibraries, ignore -custom, -cclib and -ccopt options potentially contained
in the libraries (if these options were given when building the libraries). This can be useful
if a library contains incorrect specifications of C libraries or C options; in this case, during
linking, set -noautolink and pass the correct C libraries and options on the command line.
Chapter 11. Batch compilation (ocamlc) 235
-nolabels
Ignore non-optional labels in types. Labels cannot be used in applications, and parameter
order becomes strict.
-nostdlib
Do not include the standard library directory in the list of directories searched for compiled
interface files (.cmi), compiled object code files (.cmo), libraries (.cma), and C libraries
specified with -cclib -lxxx. See also option -I.
-o exec-file
Specify the name of the output file produced by the compiler. The default output name is
a.out under Unix and camlprog.exe under Windows. If the -a option is given, specify the
name of the library produced. If the -pack option is given, specify the name of the packed
object file produced. If the -output-obj or -output-complete-obj options are given, specify
the name of the output file produced. If the -c option is given, specify the name of the
object file produced for the next source file that appears on the command line.
-opaque
When the native compiler compiles an implementation, by default it produces a .cmx file
containing information for cross-module optimization. It also expects .cmx files to be present
for the dependencies of the currently compiled source, and uses them for optimization. Since
OCaml 4.03, the compiler will emit a warning if it is unable to locate the .cmx file of one of
those dependencies.
The -opaque option, available since 4.04, disables cross-module optimization information
for the currently compiled unit. When compiling .mli interface, using -opaque marks the
compiled .cmi interface so that subsequent compilations of modules that depend on it will
not rely on the corresponding .cmx file, nor warn if it is absent. When the native compiler
compiles a .ml implementation, using -opaque generates a .cmx that does not contain any
cross-module optimization information.
Using this option may degrade the quality of generated code, but it reduces compilation
time, both on clean and incremental builds. Indeed, with the native compiler, when the
implementation of a compilation unit changes, all the units that depend on it may need to
be recompiled – because the cross-module information may have changed. If the compilation
unit whose implementation changed was compiled with -opaque, no such recompilation needs
to occur. This option can thus be used, for example, to get faster edit-compile-test feedback
loops.
-open Module
Opens the given module before processing the interface or implementation files. If several
-open options are given, they are processed in order, just as if the statements open! Module1;;
... open! ModuleN;; were added at the top of each file.
-output-obj
Cause the linker to produce a C object file instead of a bytecode executable file. This is
useful to wrap OCaml code as a C library, callable from any C program. See chapter 20,
section 20.7.5. The name of the output object file must be set with the -o option. This
236
option can also be used to produce a C source file (.c extension) or a compiled shared/dynamic
library (.so extension, .dll under Windows).
-output-complete-exe
Build a self-contained executable by linking a C object file containing the bytecode program,
the OCaml runtime system and any other static C code given to ocamlc. The resulting effect
is similar to -custom, except that the bytecode is embedded in the C code so it is no longer
accessible to tools such as ocamldebug. On the other hand, the resulting binary is resistant
to strip.
-output-complete-obj
Same as -output-obj options except the object file produced includes the runtime and au-
tolink libraries.
-pack
Build a bytecode object file (.cmo file) and its associated compiled interface (.cmi) that
combines the object files given on the command line, making them appear as sub-modules of
the output .cmo file. The name of the output .cmo file must be given with the -o option.
For instance,
generates compiled files p.cmo and p.cmi describing a compilation unit having three sub-
modules A, B and C, corresponding to the contents of the object files a.cmo, b.cmo and c.cmo.
These contents can be referenced as P.A, P.B and P.C in the remainder of the program.
-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.
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module
Ast_mapper, described in section 26.1, implements the external interface of a preprocessor.
-principal
Check information path during type-checking, to make sure that all types are derived in
a principal way. When using labelled arguments and/or polymorphic methods, this flag is
required to ensure future versions of the compiler will be able to infer types correctly, even
if internal algorithms change. All programs accepted in -principal mode are also accepted
in the default mode with equivalent types, but different binary signatures, and this may slow
down type checking; yet it is a good idea to use it once before publishing source code.
-rectypes
Allow arbitrary recursive types during type-checking. By default, only recursive types where
the recursion goes through an object type are supported. Note that once you have created
an interface using this flag, you must use it again for all dependencies.
Chapter 11. Batch compilation (ocamlc) 237
-runtime-variant suffix
Add the suffix string to the name of the runtime library used by the program. Currently, only
one such suffix is supported: d, and only if the OCaml compiler was configured with option
-with-debug-runtime. This suffix gives the debug version of the runtime, which is useful for
debugging pointer problems in low-level code such as C stubs.
-stop-after pass
Stop compilation after the given compilation pass. The currently supported passes are:
parsing, typing.
-safe-string
Enforce the separation between types string and bytes, thereby making strings read-only.
This is the default.
-short-paths
When a type is visible under several module-paths, use the shortest one when printing the
type’s name in inferred interfaces and error and warning messages. Identifier names starting
with an underscore _ or containing double underscores __ incur a penalty of +10 when
computing their length.
-strict-sequence
Force the left-hand part of each sequence to have type unit.
-strict-formats
Reject invalid formats that were accepted in legacy format implementations. You should use
this flag to detect and fix such invalid formats, as they will be rejected by future OCaml
versions.
-unboxed-types
When a type is unboxable (i.e. a record with a single argument or a concrete datatype
with a single constructor of one argument) it will be unboxed unless annotated with
[@@ocaml.boxed].
-no-unboxed-types
When a type is unboxable it will be boxed unless annotated with [@@ocaml.unboxed]. This
is the default.
-unsafe
Turn bound checking off for 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. Additionally, turn
off the check for zero divisor in integer division and modulus operations. With -unsafe, an
integer division (or modulus) by zero can halt the program or continue with an unspecified
result instead of raising a Division_by_zero exception.
-unsafe-string
Identify the types string and bytes, thereby making strings writable. This is intended for
compatibility with old source code and should not be used with new software.
238
-use-runtime runtime-name
Generate a bytecode executable file that can be executed on the custom runtime system
runtime-name, built earlier with ocamlc -make-runtime runtime-name. See section 20.1.6
for more information.
-v Print the version number of the compiler and the location of the standard library directory,
then exit.
-verbose
Print all external commands before they are executed, in particular invocations of the C
compiler and linker in -custom mode. Useful to debug C library problems.
-version or -vnum
Print the version number of the compiler in short form (e.g. 3.11.0), then exit.
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each
warning can be enabled or disabled, and each warning can be fatal or non-fatal. If a warning
is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal).
If a warning is enabled, it is displayed normally by the compiler whenever the source code
triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying
it.
The warning-list argument is a sequence of warning specifiers, with no separators between
them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or
lowercase.
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or
lowercase.
Chapter 11. Batch compilation (ocamlc) 239
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be
uppercase or lowercase.
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below),
as follows:
+name
Enable warning name.
-name
Disable warning name.
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warn-
ings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3 Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional con-
structors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is
not a function, see warning number 5).
240
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
20 ignored-extra-argument
Unused function argument.
21 nonreturning-statement
Non-returning statement.
22 preprocessor
Preprocessor warning.
23 useless-record-with
Useless record with clause.
24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.
25 Ignored: now part of warning 8.
26 unused-var
Suspicious unused variable: unused variable that is bound with let or as, and doesn’t
start with an underscore (_) character.
27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with let nor as, and
doesn’t start with an underscore (_) character.
28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.
29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
Chapter 11. Batch compilation (ocamlc) 241
30 duplicate-definitions
Two labels or constructors of the same name are defined in two mutually recursive types.
31 module-linked-twice
A module is linked twice in the same executable.
32 unused-value-declaration
Unused value declaration.
33 unused-open
Unused open statement.
34 unused-type-declaration
Unused type declaration.
35 unused-for-index
Unused for-loop index.
36 unused-ancestor
Unused ancestor variable.
37 unused-constructor
Unused constructor.
38 unused-extension
Unused extension constructor.
39 unused-rec-flag
Unused rec flag.
40 name-out-of-scope
Constructor or label name used out of scope.
41 ambiguous-name
Ambiguous constructor or label name.
42 disambiguated-name
Disambiguated constructor or label name (compatibility warning).
43 nonoptional-label
Nonoptional label applied as optional.
44 open-shadow-identifier
Open statement shadows an already defined identifier.
45 open-shadow-label-constructor
Open statement shadows an already defined label or constructor.
46 bad-env-variable
Error in environment variable.
47 attribute-payload
Illegal attribute payload.
48 eliminated-optional-arguments
Implicit elimination of optional arguments.
49 no-cmi-file
Absent cmi file when looking up module alias.
242
50 unexpected-docstring
Unexpected documentation comment.
51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute
52 fragile-literal-pattern (see 11.5.3)
Fragile constant pattern.
53 misplaced-attribute
Attribute cannot appear in this context.
54 duplicated-attribute
Attribute used more than once on an expression.
55 inlining-impossible
Inlining impossible.
56 unreachable-case
Unreachable case in a pattern-matching (based on type information).
57 ambiguous-var-in-pattern-guard (see 11.5.4)
Ambiguous or-pattern variables under guard.
58 no-cmx-file
Missing cmx file.
59 flambda-assignment-to-non-mutable-value
Assignment to non-mutable value.
60 unused-module
Unused module declaration.
61 unboxable-type-in-prim-decl
Unboxable type in primitive declaration.
62 constraint-on-gadt
Type constraint on GADT type declaration.
63 erroneous-printed-signature
Erroneous printed signature.
64 unsafe-array-syntax-without-parsing
-unsafe used with a preprocessor returning a syntax tree.
65 redefining-unit
Type declaration defining a new ’()’ constructor.
66 unused-open-bang
Unused open! statement.
67 unused-functor-parameter
Unused functor parameter.
68 match-on-mutable-state-prevent-uncurry
Pattern-matching depending on mutable state prevents the remaining arguments from
being uncurried.
Chapter 11. Batch compilation (ocamlc) 243
69 unused-field
Unused record field.
70 missing-mli
Missing interface file.
A all warnings
C warnings 1, 2.
D Alias for warning 3.
E Alias for warning 4.
F Alias for warning 5.
K warnings 32, 33, 34, 35, 36, 37, 38, 39.
L Alias for warning 6.
M Alias for warning 7.
P Alias for warning 8.
R Alias for warning 9.
S Alias for warning 10.
U warnings 11, 12.
V Alias for warning 13.
X warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.
Y Alias for warning 26.
Z Alias for warning 27.
-warn-error warning-list
Mark as fatal the warnings specified in the argument warning-list. The compiler will stop
with an error when one of these warnings is emitted. The warning-list has the same meaning
as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as
fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign
both enables and marks as fatal the corresponding warnings.
Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error
in production code, because this can break your build when future versions of OCaml add
some new warnings.
The default setting is -warn-error -a+31 (only warning 31 is fatal).
-warn-help
Show the description of all available warning numbers.
-where
Print the location of the standard library, then exit.
244
-with-runtime
Include the runtime system in the generated program. This is the default.
-without-runtime
The compiler does not include the runtime system (nor a reference to it) in the generated
program; it must be supplied separately.
- file
Process file as a file name, even if it starts with a dash (-) character.
-help or –help
Display a short usage summary and exit.
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 named Mod.cmi or mod.cmi 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.
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 gener-
alized (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, general-
ization 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 for all variables occurring
in contravariant or non-variant branches of the type. For instance, if the type of a non-value
is 'a list the variable is generalizable (list is a covariant type constructor), but not in
'a list -> 'a list (the left branch of -> is contravariant) or 'a ref (ref is non-variant).
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 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 = List.sort Stdlib.compare
(* inferred type 'a list -> 'a list, with 'a not generalized *)
write
let sort_int_list = (List.sort Stdlib.compare : 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 generalized *)
write
let map_length lv = List.map Array.length lv
Chapter 11. Batch compilation (ocamlc) 247
labels are ignored and non-optional parameters are matched in their definition order. Optional
arguments are defaulted.
let f ~x ~y = x + y
let test = f 2 3
This support for labels-omitted application was introduced when labels were added to OCaml,
to ease the progressive introduction of labels in a codebase. However, it has the downside of
weakening the labeling discipline: if you use labels to prevent callers from mistakenly reordering
two parameters of the same type, labels-omitted make this mistake possible again.
Warning 6 warns when labels-omitted applications are used, to discourage their use. When
labels were introduced, this warning was not enabled by default, so users would use labels-omitted
applications, often without noticing.
Over time, it has become idiomatic to enable this warning to avoid argument-order mistakes.
The warning is now on by default, since OCaml 4.13. Labels-omitted applications are not rec-
ommended anymore, but users wishing to preserve this transitory style can disable the warning
explicitly.
try ...
with Invalid_argument "arrays must have the same length" -> ...
This may require some care: if the scrutinee may return several different cases of the same
pattern, or raise distinct instances of the same exception, you may need to modify your code to
separate those several cases.
For example,
250
This chapter describes the toplevel system for OCaml, that permits interactive use of the OCaml
system through a read-eval-print loop (REPL). In this mode, the system repeatedly reads OCaml
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.
Input to the toplevel can span several lines. It is terminated by ;; (a double-semicolon). The
toplevel input consists in one or several toplevel phrases, with the following syntax:
A phrase can consist of a definition, like 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 value expression (section 9.7). It is simply evaluated without
performing any bindings, and its value 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 12.2.
Unix:
The toplevel system is started by the command ocaml, as follows:
options are described below. objects are filenames ending in .cmo or .cma; they are loaded
into the interpreter immediately after options are set. scriptfile is any file name not ending
in .cmo or .cma.
251
252
If no scriptfile is given on the command line, the toplevel system enters interactive mode:
phrases are read on standard input, results are printed on standard output, errors on stan-
dard error. End-of-file on standard input terminates ocaml (see also the #quit directive in
section 12.2).
On start-up (before the first phrase is read), if the file .ocamlinit exists in the current
directory, its contents are read as a sequence of OCaml phrases and executed as per
the #use directive described in section 12.2. The evaluation outcode for each phrase
are not displayed. If the current directory does not contain an .ocamlinit file, the file
XDG_CONFIG_HOME/ocaml/init.ml is looked up according to the XDG base directory
specification and used instead (on Windows this is skipped). If that file doesn’t exist then
an [.ocamlinit] file in the users’ home directory (determined via environment variable HOME)
is used if existing.
The toplevel system does not perform line editing, but it can easily be used in conjunction
with an external line editor such as ledit, or rlwrap. An improved toplevel, utop, is also
available. Another option is to use ocaml under Gnu Emacs, which gives the full editing
power of Emacs (command run-caml from library inf-caml).
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.
If scriptfile is given on the command-line to ocaml, the toplevel system enters script mode:
the contents of the file are read as a sequence of OCaml phrases and executed, as per the
#use directive (section 12.2). The outcome of the evaluation is not printed. On reaching the
end of file, the ocaml command exits immediately. No commands are read from standard
input. Sys.argv is transformed, ignoring all OCaml parameters, and starting with the script
file name in Sys.argv.(0).
In script mode, the first line of the script is ignored if it starts with #!. Thus, it should be
possible to make the script itself executable and put as first line #!/usr/local/bin/ocaml,
thus calling the toplevel system automatically when the script is run. However, ocaml itself
is a #! script on most installations of OCaml, and Unix kernels usually do not handle nested
#! scripts. A better solution is to put the following as the first line of the script:
#!/usr/local/bin/ocamlrun /usr/local/bin/ocaml
12.1 Options
The following command-line options are recognized by the ocaml command.
-absname
Force error messages to show absolute paths for file names.
-args filename
Read additional newline-terminated command line arguments from filename. It is not possible
to pass a scriptfile via file to the toplevel.
Chapter 12. The toplevel system or REPL (ocaml) 253
-args0 filename
Read additional null character terminated command line arguments from filename. It is not
possible to pass a scriptfile via file to the toplevel.
-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. See also option -nostdlib.
If the given directory starts with +, it is taken relative to the standard library directory. For
instance, -I +unix adds the subdirectory unix of the standard library to the search path.
Directories can also be added to the list once the toplevel is running with the #directory
directive (section 12.2).
-init file
Load the given file instead of the default initialization file. The default file is .ocamlinit in
the current directory if it exists, otherwise XDG_CONFIG_HOME/ocaml/init.ml or .ocamlinit
in the user’s home directory.
-labels
Labels are not ignored in types, labels may be used in applications, and labelled parameters
can be given in any order. This is the default.
-no-app-funct
Deactivates the applicative behaviour of functors. With this option, each functor application
generates new types in its result and applying the same functor twice to the same argument
yields two incompatible structures.
-noassert
Do not compile assertion checks. Note that the special form assert false is always compiled
because it is typed specially.
-nolabels
Ignore non-optional labels in types. Labels cannot be used in applications, and parameter
order becomes strict.
-noprompt
Do not display any prompt when waiting for input.
-nopromptcont
Do not display the secondary prompt when waiting for continuation lines in multi-line inputs.
This should be used e.g. when running ocaml in an emacs window.
-nostdlib
Do not include the standard library directory in the list of directories searched for source and
compiled files.
254
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module
Ast_mapper, described in section 26.1, implements the external interface of a preprocessor.
-principal
Check information path during type-checking, to make sure that all types are derived in
a principal way. When using labelled arguments and/or polymorphic methods, this flag is
required to ensure future versions of the compiler will be able to infer types correctly, even
if internal algorithms change. All programs accepted in -principal mode are also accepted
in the default mode with equivalent types, but different binary signatures, and this may slow
down type checking; yet it is a good idea to use it once before publishing source code.
-rectypes
Allow arbitrary recursive types during type-checking. By default, only recursive types where
the recursion goes through an object type are supported.
-safe-string
Enforce the separation between types string and bytes, thereby making strings read-only.
This is the default.
-short-paths
When a type is visible under several module-paths, use the shortest one when printing the
type’s name in inferred interfaces and error and warning messages. Identifier names starting
with an underscore _ or containing double underscores __ incur a penalty of +10 when
computing their length.
-stdin
Read the standard input as a script file rather than starting an interactive session.
-strict-sequence
Force the left-hand part of each sequence to have type unit.
-strict-formats
Reject invalid formats that were accepted in legacy format implementations. You should use
this flag to detect and fix such invalid formats, as they will be rejected by future OCaml
versions.
-unsafe
Turn bound checking off for 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.
-unsafe-string
Identify the types string and bytes, thereby making strings writable. This is intended for
compatibility with old source code and should not be used with new software.
-v Print the version number of the compiler and the location of the standard library directory,
then exit.
Chapter 12. The toplevel system or REPL (ocaml) 255
-verbose
Print all external commands before they are executed, Useful to debug C library problems.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-no-version
Do not print the version banner at startup.
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each
warning can be enabled or disabled, and each warning can be fatal or non-fatal. If a warning
is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal).
If a warning is enabled, it is displayed normally by the compiler whenever the source code
triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying
it.
The warning-list argument is a sequence of warning specifiers, with no separators between
them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or
lowercase.
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or
lowercase.
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be
uppercase or lowercase.
256
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below),
as follows:
+name
Enable warning name.
-name
Disable warning name.
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warn-
ings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3 Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional con-
structors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is
not a function, see warning number 5).
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
Chapter 12. The toplevel system or REPL (ocaml) 257
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
20 ignored-extra-argument
Unused function argument.
21 nonreturning-statement
Non-returning statement.
22 preprocessor
Preprocessor warning.
23 useless-record-with
Useless record with clause.
24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.
25 Ignored: now part of warning 8.
26 unused-var
Suspicious unused variable: unused variable that is bound with let or as, and doesn’t
start with an underscore (_) character.
27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with let nor as, and
doesn’t start with an underscore (_) character.
28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.
29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
30 duplicate-definitions
Two labels or constructors of the same name are defined in two mutually recursive types.
31 module-linked-twice
A module is linked twice in the same executable.
258
32 unused-value-declaration
Unused value declaration.
33 unused-open
Unused open statement.
34 unused-type-declaration
Unused type declaration.
35 unused-for-index
Unused for-loop index.
36 unused-ancestor
Unused ancestor variable.
37 unused-constructor
Unused constructor.
38 unused-extension
Unused extension constructor.
39 unused-rec-flag
Unused rec flag.
40 name-out-of-scope
Constructor or label name used out of scope.
41 ambiguous-name
Ambiguous constructor or label name.
42 disambiguated-name
Disambiguated constructor or label name (compatibility warning).
43 nonoptional-label
Nonoptional label applied as optional.
44 open-shadow-identifier
Open statement shadows an already defined identifier.
45 open-shadow-label-constructor
Open statement shadows an already defined label or constructor.
46 bad-env-variable
Error in environment variable.
47 attribute-payload
Illegal attribute payload.
48 eliminated-optional-arguments
Implicit elimination of optional arguments.
49 no-cmi-file
Absent cmi file when looking up module alias.
50 unexpected-docstring
Unexpected documentation comment.
51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute
Chapter 12. The toplevel system or REPL (ocaml) 259
C warnings 1, 2.
D Alias for warning 3.
E Alias for warning 4.
F Alias for warning 5.
K warnings 32, 33, 34, 35, 36, 37, 38, 39.
L Alias for warning 6.
M Alias for warning 7.
P Alias for warning 8.
R Alias for warning 9.
S Alias for warning 10.
U warnings 11, 12.
V Alias for warning 13.
X warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.
Y Alias for warning 26.
Z Alias for warning 27.
-warn-error warning-list
Mark as fatal the warnings specified in the argument warning-list. The compiler will stop
with an error when one of these warnings is emitted. The warning-list has the same meaning
as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as
fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign
both enables and marks as fatal the corresponding warnings.
Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error
in production code, because this can break your build when future versions of OCaml add
some new warnings.
The default setting is -warn-error -a+31 (only warning 31 is fatal).
-warn-help
Show the description of all available warning numbers.
- file
Use file as a script file name, even when it starts with a hyphen (-).
-help or –help
Display a short usage summary and exit.
Unix:
The following environment variables are also consulted:
Chapter 12. The toplevel system or REPL (ocaml) 261
OCAMLTOP_INCLUDE_PATH
Additional directories to search for compiled object code files (.cmi, .cmo and .cma).
The specified directories are considered from left to right, after the include directories
specified on the command line via -I have been searched. Available since OCaml 4.08.
OCAMLTOP_UTF_8
When printing string values, non-ascii bytes ( > \0x7E) are printed as decimal escape
sequence if OCAMLTOP_UTF_8 is set to false. Otherwise, they are printed unescaped.
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.
XDG_CONFIG_HOME, HOME
.ocamlinit lookup procedure (see above).
General
#help;;
Prints a list of all available directives, with corresponding argument type if appropriate.
#quit;;
Exit the toplevel loop and terminate the ocaml command.
Loading codes
#cd "dir-name";;
Change the current working directory.
#directory "dir-name";;
Add the given directory to the list of directories searched for source and compiled files.
#remove_directory "dir-name";;
Remove the given directory from the list of directories searched for source and compiled
files. Do nothing if the list does not contain the given directory.
#load "file-name";;
Load in memory a bytecode object file (.cmo file) or library file (.cma file) produced by
the batch compiler ocamlc.
262
#load_rec "file-name";;
Load in memory a bytecode object file (.cmo file) or library file (.cma file) produced by
the batch compiler ocamlc. When loading an object file that depends on other modules
which have not been loaded yet, the .cmo files for these modules are searched and loaded
as well, recursively. The loading order is not specified.
#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.
#use_output "command";;
Execute a command and evaluate its output as if it had been captured to a file and
passed to #use.
#mod_use "file-name";;
Similar to #use but also wrap the code into a top-level module of the same name as
capitalized file name without extensions, following semantics of the compiler.
For directives that take file names as arguments, if the given file name specifies no directory,
the file is searched in the following directories:
1. In script mode, the directory containing the script currently executing; in interactive
mode, the current working directory.
2. Directories added with the #directory directive.
3. Directories given on the command line with -I options.
4. The standard library directory.
Environment queries
#show_class class-path;;
#show_class_type class-path;;
#show_exception ident;;
#show_module module-path;;
#show_module_type modtype-path;;
#show_type typeconstr;;
#show_val value-path;;
Print the signature of the corresponding component.
#show ident;;
Print the signatures of components with name ident in all the above categories.
Pretty-printing
#install_printer printer-name;;
This directive registers the function named printer-name (a value path) as a printer for
values whose types match the argument type of the function. That is, the toplevel loop
will call printer-name when it has such a value to print.
Chapter 12. The toplevel system or REPL (ocaml) 263
The printing function printer-name should have type Format.formatter ->t -> unit,
where t is the type for the values to be printed, and should output its textual represen-
tation for the value of type t on the given formatter, using the functions provided by the
Format library. For backward compatibility, printer-name can also have type t-> unit
and should then output on the standard formatter, but this usage is deprecated.
#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).
#remove_printer printer-name;;
Remove the named function from the table of toplevel printers.
Tracing
#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.
#untrace function-name;;
Stop tracing the given function.
#untrace_all;;
Stop tracing all functions traced so far.
Compiler options
#labels bool;;
Ignore labels in function types if argument is false, or switch back to default behaviour
(commuting style) if argument is true.
#ppx "file-name";;
After parsing, pipe the abstract syntax tree through the preprocessor command.
#principal bool;;
If the argument is true, check information paths during type-checking, to make sure
that all types are derived in a principal way. If the argument is false, do not check
information paths.
#rectypes;;
Allow arbitrary recursive types during type-checking. Note: once enabled, this option
cannot be disabled because that would lead to unsoundness of the type system.
264
#warn_error "warning-list";;
Treat as errors the warnings enabled by the argument and as normal warnings the
warnings disabled by the argument.
#warnings "warning-list";;
Enable or disable warnings according to the argument.
This creates the bytecode file mytoplevel, containing the OCaml 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;;
12.5.1 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 11.
-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 11.
-custom
Link in “custom runtime” mode. See the corresponding option for ocamlc, in chapter 11.
-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 default is a.out.
266
The ocamlrun command executes bytecode files produced by the linking phase of the ocamlc
command.
13.1 Overview
The ocamlrun command comprises three main parts: the bytecode interpreter, that actually ex-
ecutes 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:
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 OCaml 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
arg 1 to arg n .
As mentioned in chapter 11, 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 a.out is a bytecode executable file,
works exactly as
Notice that it is not possible to pass options to ocamlrun when invoking a.out directly.
Windows:
Under several versions of Windows, bytecode executable files are self-executable only if their
name ends in .exe. It is recommended to always give .exe names to bytecode executables,
e.g. compile with ocamlc -o myprog.exe ... rather than ocamlc -o myprog ....
267
268
13.2 Options
The following command-line options are recognized by ocamlrun.
-b When the program aborts due to an uncaught exception, print a detailed “back trace” of the
execution, showing where the exception was raised and which function calls were outstanding
at this point. The back trace is printed only if the bytecode executable contains debugging
information, i.e. was compiled and linked with the -g option to ocamlc set. This is equivalent
to setting the b flag in the OCAMLRUNPARAM environment variable (see below).
-config
Print the version number of ocamlrun and a detailed summary of its configuration, then exit.
-I dir
Search the directory dir for dynamically-loaded libraries, in addition to the standard search
path (see section 13.3).
-m Print the magic number of the bytecode executable given as argument and exit.
-M Print the magic number expected by this version of the runtime and exit.
-p Print the names of the primitives known to this version of ocamlrun and exit.
-t Increments the trace level for the debug runtime (ignored otherwise).
-v Direct the memory manager to print some progress messages on standard error. This is
equivalent to setting v=61 in the OCAMLRUNPARAM environment variable (see below).
-version
Print version string and exit.
-vnum
Print short version number and exit.
The following environment variables are also consulted:
CAML_LD_LIBRARY_PATH
Additional directories to search for dynamically-loaded libraries (see section 13.3).
OCAMLLIB
The directory containing the OCaml standard library. (If OCAMLLIB is not set, CAMLLIB will
be used instead.) Used to locate the ld.conf configuration file for dynamic loading (see
section 13.3). If not set, default to the library directory specified when compiling OCaml.
OCAMLRUNPARAM
Set the runtime system options and garbage collection parameters. (If OCAMLRUNPARAM is
not set, CAMLRUNPARAM will be used instead.) This variable must be a sequence of parameter
specifications separated by commas. For convenience, commas at the beginning of the variable
are ignored, and multiple runs of commas are interpreted as a single one. A parameter
specification is an option letter followed by an = sign, a decimal number (or an hexadecimal
number prefixed by 0x), and an optional multiplier. The options are documented below; the
last six correspond to the fields of the control record documented in section 25.20.
Chapter 13. The runtime system (ocamlrun) 269
b (backtrace) Trigger the printing of a stack backtrace when an uncaught exception aborts
the program. An optional argument can be provided: b=0 turns backtrace printing off;
b=1 is equivalent to b and turns backtrace printing on; b=2 turns backtrace printing
on and forces the runtime system to load debugging information at program startup
time instead of at backtrace printing time. b=2 can be used if the runtime is unable to
load debugging information at backtrace printing time, for example if there are no file
descriptors available.
p (parser trace) Turn on debugging support for ocamlyacc-generated parsers. When this
option is on, the pushdown automaton that executes the parsers prints a trace of its
actions. This option takes no argument.
R (randomize) Turn on randomization of all hash tables by default (see section 25.22).
This option takes no argument.
h The initial size of the major heap (in words).
a (allocation_policy) The policy used for allocating in the OCaml heap. Possible values
are 0 for the next-fit policy, 1 for the first-fit policy, and 2 for the best-fit policy. The
default is 2 (best-fit). See the Gc module documentation for details.
s (minor_heap_size) Size of the minor heap. (in words)
i (major_heap_increment) Default size increment for the major heap. (in words)
o (space_overhead) The major GC speed setting. See the Gc module documentation for
details.
O (max_overhead) The heap compaction trigger setting.
l (stack_limit) The limit (in words) of the stack size. This is only relevant to the byte-
code runtime, as the native code runtime uses the operating system’s stack.
v (verbose) What GC messages to print to stderr. This is a sum of values selected from
the following:
1 (= 0x001)
Start and end of major GC cycle.
2 (= 0x002)
Minor collection and major GC slice.
4 (= 0x004)
Growing and shrinking of the heap.
8 (= 0x008)
Resizing of stacks and memory manager tables.
16 (= 0x010)
Heap compaction.
32 (= 0x020)
Change of GC parameters.
64 (= 0x040)
Computation of major GC slice size.
128 (= 0x080)
Calling of finalization functions
270
256 (= 0x100)
Startup messages (loading the bytecode executable file, resolving shared libraries).
512 (= 0x200)
Computation of compaction-triggering condition.
1024 (= 0x400)
Output GC statistics at program exit.
c (cleanup_on_exit) Shut the runtime down gracefully on exit (see caml_shutdown in
section 20.7.5). The option also enables pooling (as in caml_startup_pooled). This
mode can be used to detect leaks with a third-party memory debugger.
M (custom_major_ratio) Target ratio of floating garbage to major heap size for out-of-
heap memory held by custom values (e.g. bigarrays) located in the major heap. The
GC speed is adjusted to try to use this much memory for dead values that are not yet
collected. Expressed as a percentage of major heap size. Default: 44. Note: this only
applies to values allocated with caml_alloc_custom_mem.
m (custom_minor_ratio) Bound on floating garbage for out-of-heap memory held by cus-
tom values in the minor heap. A minor GC is triggered when this much memory is held by
custom values located in the minor heap. Expressed as a percentage of minor heap size.
Default: 100. Note: this only applies to values allocated with caml_alloc_custom_mem.
n (custom_minor_max_size) Maximum amount of out-of-heap memory for each
custom value allocated in the minor heap. When a custom value is allocated
on the minor heap and holds more than this many bytes, only this value is
counted against custom_minor_ratio and the rest is directly counted against
custom_major_ratio. Default: 8192 bytes. Note: this only applies to values allocated
with caml_alloc_custom_mem.
export OCAMLRUNPARAM='b,s=256k,v=0x015'
tells a subsequent ocamlrun to print backtraces for uncaught exceptions, set its initial minor
heap size to 1 megabyte and print a message at the start of each major GC cycle, when the
heap size changes, and when compaction is triggered.
CAMLRUNPARAM
If OCAMLRUNPARAM is not found in the environment, then CAMLRUNPARAM will be used instead.
If CAMLRUNPARAM is also not found, then the default values will be used.
PATH
List of directories searched to find the bytecode executable file.
Chapter 13. The runtime system (ocamlrun) 271
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, along with its string, byte sequence, and
integer arguments (arguments of more complex types are not correctly printed). To locate
the context of the uncaught exception, compile the program with the -g option and either
run it again under the ocamldebug debugger (see chapter 18), or run it with ocamlrun -b or
with the OCAMLRUNPARAM environment variable set to b=1.
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, string or byte sequence, 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,
or with the OCAMLRUNPARAM environment variable set to v=63. 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, string or byte sequence.
Chapter 14
This chapter describes the OCaml high-performance native-code compiler ocamlopt, which com-
piles OCaml source files to native code object files and links 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 ocamlopt with bytecode object
files produced by ocamlc: 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.
• Arguments ending in .mli are taken to be source files for compilation unit interfaces. In-
terfaces 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 informa-
tion 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 or .obj file, ocamlopt
assumes that it contains code compiled from C, not from OCaml).
The implementation is checked against the interface file x.mli (if it exists) as described in
the manual for ocamlc (chapter 11).
273
274
• 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
OCaml standard library, to 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/.lib) a set of object files (.cmx and .o/.obj 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/.obj object file.
This object file is linked with the program.
• Arguments ending in .o, .a or .so (.obj, .lib and .dll under Windows) 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 or Windows executable file. It does not need
ocamlrun to run.
The compiler is able to emit some information on its internal stages:
• .cmt files for the implementation of the compilation unit and .cmti for signatures if the
option -bin-annot is passed to it (see the description of -bin-annot below). Each such
file contains a typed abstract syntax tree (AST), that is produced during the type checking
procedure. This tree contains all available information about the location and the specific
type of each term in the source file. The AST is partial if type checking was unsuccessful.
These .cmt and .cmti files are typically useful for code inspection tools.
• .cmir-linear files for the implementation of the compilation unit if the option
-save-ir-after scheduling is passed to it. Each such file contains a low-level intermediate
representation, produced by the instruction scheduling pass.
An external tool can perform low-level optimisations, such as code layout, by transforming
a .cmir-linear file. To continue compilation, the compiler can be invoked with (a possibly
modified) .cmir-linear file as an argument, instead of the corresponding source file.
14.2 Options
The following command-line options are recognized by ocamlopt. The options -pack, -a, -shared,
-c, -output-obj and -output-complete-obj are mutually exclusive.
-a Build a library(.cmxa and .a/.lib files) with the object files (.cmx and .o/.obj files) given
on the command line, instead of linking them into an executable file. The name of the library
must be set with the -o option.
Chapter 14. Native-code compilation (ocamlopt) 275
If -cclib or -ccopt options are passed on the command line, these options are stored in the
resulting .cmxalibrary. Then, linking with this library automatically adds back the -cclib
and -ccopt options as if they had been provided on the command line, unless the -noautolink
option is given.
-absname
Force error messages to show absolute paths for file names.
-annot
Deprecated since OCaml 4.11. Please use -bin-annot instead.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-bin-annot
Dump detailed information about the compilation (types, bindings, tail-calls, etc) in bi-
nary format. The information for file src.ml (resp. src.mli) is put into file src.cmt (resp.
src.cmti). In case of a type error, dump all the information inferred by the type-checker be-
fore the error. The *.cmt and *.cmti files produced by -bin-annot contain more information
and are much more compact than the files produced by -annot.
-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.
-cc ccomp
Use ccomp as the C linker called to build the final executable and as the C compiler for
compiling .c source files.
-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.
-color mode
Enable or disable colors in compiler messages (especially warnings and errors). The following
modes are supported:
auto
use heuristics to enable colors only if the output supports them (an ANSI-compatible
tty terminal);
always
enable colors unconditionally;
276
never
disable color output.
The default setting is ’auto’, and the current heuristic checks that the TERM environment
variable exists and is not empty or dumb, and that ’isatty(stderr)’ holds.
The environment variable OCAML_COLOR is considered if -color is not provided. Its values
are auto/always/never as above.
-error-style mode
Control the way error messages and warnings are printed. The following modes are supported:
short
only print the error and its location;
contextual
like short, but also display the source code snippet corresponding to the location of the
error.
-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.
-config
Print the version number of ocamlopt and a detailed summary of its configuration, then exit.
-config-var var
Print the value of a specific configuration variable from the -config output, then exit. If the
variable does not exist, the exit code is non-zero. This option is only available since OCaml
4.08, so script authors should have a fallback for older versions.
-depend ocamldep-args
Compute dependencies, as the ocamldep command would do. The remaining arguments are
interpreted as if they were given to the ocamldep command.
-for-pack module-path
Generate an object file (.cmx and .o/.obj files) that can later be included as a sub-module
(with the given access path) of a compilation unit constructed with -pack. For instance,
ocamlopt -for-pack P -c A.ml will generate a..cmx and a.o files that can later be used with
ocamlopt -pack -o P.cmx a.cmx. Note: you can still pack a module that was compiled without
-for-pack but in this case exceptions will be printed with the wrong names.
-g Add debugging information while compiling and linking. This option is required in order
to produce stack backtraces when the program terminates on an uncaught exception (see
section 13.2).
Chapter 14. Native-code compilation (ocamlopt) 277
-i Cause the compiler to print all defined names (with their inferred types or their definitions)
when compiling an implementation (.ml file). No compiled files (.cmo and .cmi files) are
produced. 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),
compiled object code files (.cmx), and libraries (.cmxa). 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. See also option -nostdlib.
If the given directory starts with +, it is taken relative to the standard library directory. For
instance, -I +unix adds the subdirectory unix of the standard library to the search path.
-impl filename
Compile the file filename as an implementation file, even if its extension is not .ml.
-inline n
Set aggressiveness of inlining to n, where n is a positive integer. Specifying -inline 0
prevents all functions from being inlined, except those whose body is smaller than the call
site. Thus, inlining causes no expansion in code size. The default aggressiveness, -inline 1,
allows slightly larger functions to be inlined, resulting in a slight expansion in code size.
Higher values for the -inline option cause larger and larger functions to become candidate
for inlining, but can result in a serious increase in code size.
-intf filename
Compile the file filename as an interface file, even if its extension is not .mli.
-intf-suffix string
Recognize file names ending with string as interface files (instead of the default .mli).
-labels
Labels are not ignored in types, labels may be used in applications, and labelled parameters
can be given in any order. This is the default.
-linkall
Force 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 (option -a), setting the -linkall option
forces all subsequent links of programs involving that library to link all the modules contained
in the library. When compiling a module (option -c), setting the -linkall option ensures
that this module will always be linked if it is put in a library and this library is linked.
-linscan
Use linear scan register allocation. Compiling with this allocator is faster than with the usual
graph coloring allocator, sometimes quite drastically so for long functions and modules. On
the other hand, the generated code can be a bit slower.
278
-match-context-rows
Set the number of rows of context used for optimization during pattern matching compilation.
The default value is 32. Lower values cause faster compilation, but less optimized code. This
advanced option is meant for use in the event that a pattern-match-heavy program leads to
significant increases in compilation time.
-no-alias-deps
Do not record dependencies for module aliases. See section 10.8 for more information.
-no-app-funct
Deactivates the applicative behaviour of functors. With this option, each functor application
generates new types in its result and applying the same functor twice to the same argument
yields two incompatible structures.
-no-float-const-prop
Deactivates the constant propagation for floating-point operations. This option should be
given if the program changes the float rounding mode during its execution.
-noassert
Do not compile assertion checks. Note that the special form assert false is always compiled
because it is typed specially. This flag has no effect when linking already-compiled files.
-noautolink
When linking .cmxalibraries, ignore -cclib and -ccopt options potentially contained in
the libraries (if these options were given when building the libraries). This can be useful
if a library contains incorrect specifications of C libraries or C options; in this case, during
linking, set -noautolink and pass the correct C libraries and options on the command line.
-nodynlink
Allow the compiler to use some optimizations that are valid only for code that is statically
linked to produce a non-relocatable executable. The generated code cannot be linked to pro-
duce a shared library nor a position-independent executable (PIE). Many operating systems
produce PIEs by default, causing errors when linking code compiled with -nodynlink. Either
do not use -nodynlink or pass the option -ccopt -no-pie at link-time.
-nolabels
Ignore non-optional labels in types. Labels cannot be used in applications, and parameter
order becomes strict.
-nostdlib
Do not automatically add the standard library directory to the list of directories searched for
compiled interface files (.cmi), compiled object code files (.cmx), and libraries (.cmxa). See
also option -I.
-o exec-file
Specify the name of the output file produced by the linker. The default output name is a.out
under Unix and camlprog.exe under Windows. If the -a option is given, specify the name
of the library produced. If the -pack option is given, specify the name of the packed object
Chapter 14. Native-code compilation (ocamlopt) 279
file produced. If the -output-obj or -output-complete-obj options are given, specify the
name of the output file produced. If the -shared option is given, specify the name of plugin
file produced.
-opaque
When the native compiler compiles an implementation, by default it produces a .cmx file
containing information for cross-module optimization. It also expects .cmx files to be present
for the dependencies of the currently compiled source, and uses them for optimization. Since
OCaml 4.03, the compiler will emit a warning if it is unable to locate the .cmx file of one of
those dependencies.
The -opaque option, available since 4.04, disables cross-module optimization information
for the currently compiled unit. When compiling .mli interface, using -opaque marks the
compiled .cmi interface so that subsequent compilations of modules that depend on it will
not rely on the corresponding .cmx file, nor warn if it is absent. When the native compiler
compiles a .ml implementation, using -opaque generates a .cmx that does not contain any
cross-module optimization information.
Using this option may degrade the quality of generated code, but it reduces compilation
time, both on clean and incremental builds. Indeed, with the native compiler, when the
implementation of a compilation unit changes, all the units that depend on it may need to
be recompiled – because the cross-module information may have changed. If the compilation
unit whose implementation changed was compiled with -opaque, no such recompilation needs
to occur. This option can thus be used, for example, to get faster edit-compile-test feedback
loops.
-open Module
Opens the given module before processing the interface or implementation files. If several
-open options are given, they are processed in order, just as if the statements open! Module1;;
... open! ModuleN;; were added at the top of each file.
-output-obj
Cause the linker to produce a C object file instead of an executable file. This is useful to wrap
OCaml code as a C library, callable from any C program. See chapter 20, section 20.7.5. The
name of the output object file must be set with the -o option. This option can also be used
to produce a compiled shared/dynamic library (.so extension, .dll under Windows).
-output-complete-obj
Same as -output-obj options except the object file produced includes the runtime and au-
tolink libraries.
-pack
Build an object file (.cmx and .o/.obj files) and its associated compiled interface (.cmi)
that combines the .cmx object files given on the command line, making them appear as sub-
modules of the output .cmx file. The name of the output .cmx file must be given with the -o
option. For instance,
generates compiled files P.cmx, P.o and P.cmi describing a compilation unit having three
sub-modules A, B and C, corresponding to the contents of the object files A.cmx, B.cmx and
C.cmx. These contents can be referenced as P.A, P.B and P.C in the remainder of the program.
The .cmx object files being combined must have been compiled with the appropriate
-for-pack option. In the example above, A.cmx, B.cmx and C.cmx must have been compiled
with ocamlopt -for-pack P.
Multiple levels of packing can be achieved by combining -pack with -for-pack. Consider
the following example:
The resulting P.cmx object file has sub-modules P.Q, P.Q.A and P.B.
-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.
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module
Ast_mapper, described in section 26.1, implements the external interface of a preprocessor.
-principal
Check information path during type-checking, to make sure that all types are derived in
a principal way. When using labelled arguments and/or polymorphic methods, this flag is
required to ensure future versions of the compiler will be able to infer types correctly, even
if internal algorithms change. All programs accepted in -principal mode are also accepted
in the default mode with equivalent types, but different binary signatures, and this may slow
down type checking; yet it is a good idea to use it once before publishing source code.
-rectypes
Allow arbitrary recursive types during type-checking. By default, only recursive types where
the recursion goes through an object type are supported. Note that once you have created
an interface using this flag, you must use it again for all dependencies.
-runtime-variant suffix
Add the suffix string to the name of the runtime library used by the program. Currently, only
one such suffix is supported: d, and only if the OCaml compiler was configured with option
-with-debug-runtime. This suffix gives the debug version of the runtime, which is useful for
debugging pointer problems in low-level code such as C stubs.
-stop-after pass
Stop compilation after the given compilation pass. The currently supported passes are:
parsing, typing, scheduling, emit.
Chapter 14. Native-code compilation (ocamlopt) 281
-save-ir-after pass
Save intermediate representation after the given compilation pass to a file. The currently
supported passes and the corresponding file extensions are: scheduling (.cmir-linear).
This experimental feature enables external tools to inspect and manipulate compiler’s inter-
mediate representation of the program using compiler-libs library (see section 26).
-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.
-shared
Build a plugin (usually .cmxs) that can be dynamically loaded with the Dynlink module. The
name of the plugin must be set with the -o option. A plugin can include a number of OCaml
modules and libraries, and extra native objects (.o, .obj, .a, .lib files). Building native
plugins is only supported for some operating system. Under some systems (currently, only
Linux AMD 64), all the OCaml code linked in a plugin must have been compiled without the
-nodynlink flag. Some constraints might also apply to the way the extra native objects have
been compiled (under Linux AMD 64, they must contain only position-independent code).
-safe-string
Enforce the separation between types string and bytes, thereby making strings read-only.
This is the default.
-short-paths
When a type is visible under several module-paths, use the shortest one when printing the
type’s name in inferred interfaces and error and warning messages. Identifier names starting
with an underscore _ or containing double underscores __ incur a penalty of +10 when
computing their length.
-strict-sequence
Force the left-hand part of each sequence to have type unit.
-strict-formats
Reject invalid formats that were accepted in legacy format implementations. You should use
this flag to detect and fix such invalid formats, as they will be rejected by future OCaml
versions.
-unboxed-types
When a type is unboxable (i.e. a record with a single argument or a concrete datatype
with a single constructor of one argument) it will be unboxed unless annotated with
[@@ocaml.boxed].
-no-unboxed-types
When a type is unboxable it will be boxed unless annotated with [@@ocaml.unboxed]. This
is the default.
-unsafe
Turn bound checking off for array and string accesses (the v.(i) and s.[i] constructs).
Programs compiled with -unsafe are therefore faster, but unsafe: anything can happen if
282
the program accesses an array or string outside of its bounds. Additionally, turn off the check
for zero divisor in integer division and modulus operations. With -unsafe, an integer division
(or modulus) by zero can halt the program or continue with an unspecified result instead of
raising a Division_by_zero exception.
-unsafe-string
Identify the types string and bytes, thereby making strings writable. This is intended for
compatibility with old source code and should not be used with new software.
-v Print the version number of the compiler and the location of the standard library directory,
then exit.
-verbose
Print all external commands before they are executed, in particular invocations of the assem-
bler, C compiler, and linker. Useful to debug C library problems.
-version or -vnum
Print the version number of the compiler in short form (e.g. 3.11.0), then exit.
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each
warning can be enabled or disabled, and each warning can be fatal or non-fatal. If a warning
is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal).
If a warning is enabled, it is displayed normally by the compiler whenever the source code
triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying
it.
The warning-list argument is a sequence of warning specifiers, with no separators between
them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or
lowercase.
Chapter 14. Native-code compilation (ocamlopt) 283
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or
lowercase.
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be
uppercase or lowercase.
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below),
as follows:
+name
Enable warning name.
-name
Disable warning name.
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warn-
ings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3 Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional con-
structors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
284
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is
not a function, see warning number 5).
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
20 ignored-extra-argument
Unused function argument.
21 nonreturning-statement
Non-returning statement.
22 preprocessor
Preprocessor warning.
23 useless-record-with
Useless record with clause.
24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.
25 Ignored: now part of warning 8.
26 unused-var
Suspicious unused variable: unused variable that is bound with let or as, and doesn’t
start with an underscore (_) character.
27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with let nor as, and
doesn’t start with an underscore (_) character.
28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.
Chapter 14. Native-code compilation (ocamlopt) 285
29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
30 duplicate-definitions
Two labels or constructors of the same name are defined in two mutually recursive types.
31 module-linked-twice
A module is linked twice in the same executable.
32 unused-value-declaration
Unused value declaration.
33 unused-open
Unused open statement.
34 unused-type-declaration
Unused type declaration.
35 unused-for-index
Unused for-loop index.
36 unused-ancestor
Unused ancestor variable.
37 unused-constructor
Unused constructor.
38 unused-extension
Unused extension constructor.
39 unused-rec-flag
Unused rec flag.
40 name-out-of-scope
Constructor or label name used out of scope.
41 ambiguous-name
Ambiguous constructor or label name.
42 disambiguated-name
Disambiguated constructor or label name (compatibility warning).
43 nonoptional-label
Nonoptional label applied as optional.
44 open-shadow-identifier
Open statement shadows an already defined identifier.
45 open-shadow-label-constructor
Open statement shadows an already defined label or constructor.
46 bad-env-variable
Error in environment variable.
47 attribute-payload
Illegal attribute payload.
48 eliminated-optional-arguments
Implicit elimination of optional arguments.
286
49 no-cmi-file
Absent cmi file when looking up module alias.
50 unexpected-docstring
Unexpected documentation comment.
51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute
52 fragile-literal-pattern (see 11.5.3)
Fragile constant pattern.
53 misplaced-attribute
Attribute cannot appear in this context.
54 duplicated-attribute
Attribute used more than once on an expression.
55 inlining-impossible
Inlining impossible.
56 unreachable-case
Unreachable case in a pattern-matching (based on type information).
57 ambiguous-var-in-pattern-guard (see 11.5.4)
Ambiguous or-pattern variables under guard.
58 no-cmx-file
Missing cmx file.
59 flambda-assignment-to-non-mutable-value
Assignment to non-mutable value.
60 unused-module
Unused module declaration.
61 unboxable-type-in-prim-decl
Unboxable type in primitive declaration.
62 constraint-on-gadt
Type constraint on GADT type declaration.
63 erroneous-printed-signature
Erroneous printed signature.
64 unsafe-array-syntax-without-parsing
-unsafe used with a preprocessor returning a syntax tree.
65 redefining-unit
Type declaration defining a new ’()’ constructor.
66 unused-open-bang
Unused open! statement.
67 unused-functor-parameter
Unused functor parameter.
68 match-on-mutable-state-prevent-uncurry
Pattern-matching depending on mutable state prevents the remaining arguments from
being uncurried.
Chapter 14. Native-code compilation (ocamlopt) 287
69 unused-field
Unused record field.
70 missing-mli
Missing interface file.
A all warnings
C warnings 1, 2.
D Alias for warning 3.
E Alias for warning 4.
F Alias for warning 5.
K warnings 32, 33, 34, 35, 36, 37, 38, 39.
L Alias for warning 6.
M Alias for warning 7.
P Alias for warning 8.
R Alias for warning 9.
S Alias for warning 10.
U warnings 11, 12.
V Alias for warning 13.
X warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.
Y Alias for warning 26.
Z Alias for warning 27.
-warn-error warning-list
Mark as fatal the warnings specified in the argument warning-list. The compiler will stop
with an error when one of these warnings is emitted. The warning-list has the same meaning
as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as
fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign
both enables and marks as fatal the corresponding warnings.
Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error
in production code, because this can break your build when future versions of OCaml add
some new warnings.
The default setting is -warn-error -a+31 (only warning 31 is fatal).
-warn-help
Show the description of all available warning numbers.
-where
Print the location of the standard library, then exit.
288
-with-runtime
Include the runtime system in the generated program. This is the default.
-without-runtime
The compiler does not include the runtime system (nor a reference to it) in the generated
program; it must be supplied separately.
- file
Process file as a file name, even if it starts with a dash (-) character.
-help or –help
Display a short usage summary and exit.
Options for the 32-bit x86 architecture The 32-bit code generator for Intel/AMD x86
processors (i386 architecture) supports the following additional option:
-ffast-math
Use the processor instructions to compute trigonometric and exponential functions, instead of
calling the corresponding library routines. The functions affected are: atan, atan2, cos, log,
log10, sin, sqrt and tan. The resulting code runs faster, but the range of supported argu-
ments and the precision of the result can be reduced. In particular, trigonometric operations
cos, sin, tan have their range reduced to [−264 , 264 ].
Options for the 64-bit x86 architecture The 64-bit code generator for Intel/AMD x86
processors (amd64 architecture) supports the following additional options:
-fPIC
Generate position-independent machine code. This is the default.
-fno-PIC
Generate position-dependent machine code.
Options for the PowerPC architecture The PowerPC code generator supports the following
additional options:
-flarge-toc
Enables the PowerPC large model allowing the TOC (table of contents) to be arbitrarily
large. This is the default since 4.11.
-fsmall-toc
Enables the PowerPC small model allowing the TOC to be up to 64 kbytes per compilation
unit. Prior to 4.11 this was the default behaviour.
Chapter 14. Native-code compilation (ocamlopt) 289
OCAMLRUNPARAM
Same usage as in ocamlrun (see section 13.2), except that option l is ignored (the operating
system’s stack size limit is used instead).
CAMLRUNPARAM
If OCAMLRUNPARAM is not found in the environment, then CAMLRUNPARAM will be used instead.
If CAMLRUNPARAM is not found, then the default values will be used.
• 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.
• On ARM and PowerPC processors (32 and 64 bits), fused multiply-add (FMA) instructions
can be generated for a floating-point multiplication followed by a floating-point addition or
subtraction, as in x *. y +. z. The FMA instruction avoids rounding the intermediate
result x *. y, which is generally beneficial, but produces floating-point results that differ
slightly from those produced by the bytecode interpreter.
• The native-code compiler performs a number of optimizations that the bytecode compiler
does not perform, especially when the Flambda optimizer is active. In particular, the native-
code compiler identifies and eliminates “dead code”, i.e. computations that do not contribute
to the results of the program. For example,
contains a reference to compilation unit M when compiled to bytecode. This reference forces M
to be linked and its initialization code to be executed. The native-code compiler eliminates the
reference to M, hence the compilation unit M may not be linked and executed. A workaround
is to compile M with the -linkall flag so that it will always be linked and executed, even if
not referenced. See also the Sys.opaque_identity function from the Sys standard library
module.
• Before 4.10, stack overflows, typically caused by excessively deep recursion, are not always
turned into a Stack_overflow exception like with the bytecode compiler. The runtime system
makes a best effort to trap stack overflows and raise the Stack_overflow exception, but
sometimes it fails and a “segmentation fault” or another system fault occurs instead.
Chapter 15
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, Lam, Sethi and Ullman (Pearson, 2006), or “Lex & Yacc”, by Levine, Mason
and Brown (O’Reilly, 1992).
ocamllex lexer.mll
produces OCaml code for a lexical analyzer in file lexer.ml. This file defines one lexing func-
tion 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, respec-
tively. (See the description of module Lexing in chapter 25.)
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.)
291
292
15.1.1 Options
The following command-line options are recognized by ocamllex.
-ml Output code that does not use OCaml’s built-in automata interpreter. Instead, the automaton
is encoded by OCaml functions. This option improves performance when using the native
compiler, but decreases it when using the bytecode compiler.
-o output-file
Specify the name of the output file produced by ocamllex. The default is the input file name
with its extension replaced by .ml.
-q Quiet mode. ocamllex normally outputs informational messages to standard output. They
are suppressed if option -q is used.
-v or -version
Print version string and exit.
-vnum
Print short version number and exit.
-help or –help
Display a short usage summary and exit.
{ header }
let ident = regexp ...
[refill { refill-handler }]
rule entrypoint [arg 1 ... arg n ] =
parse regexp { action }
| ...
| regexp { action }
and entrypoint [arg 1 ... arg n ] =
parse ...
and ...
{ trailer }
Comments are delimited by (* and *), as in OCaml. The parse keyword, can be replaced by
the shortest keyword, with the semantic consequences explained below.
Refill handlers are a recent (optional) feature introduced in 4.02, documented below in subsec-
tion 15.2.7.
Chapter 15. Lexer and parser generators (ocamllex, ocamlyacc) 293
15.2.5 Actions
The actions are arbitrary OCaml expressions. They are evaluated in a context where the identifiers
defined by using the as construct are bound to subparts of the matched string. Additionally,
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.
Chapter 15. Lexer and parser generators (ocamllex, ocamlyacc) 295
Lexing.lexeme lexbuf
Return the matched string.
Lexing.lexeme_char lexbuf n
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 (i.e. the
offset of the first character of the matched string). The first character read from the input
text has offset 0.
Lexing.lexeme_end lexbuf
Return the absolute position in the input text of the end of the matched string (i.e. the offset
of the first character after the matched string). The first character read from the input text
has offset 0.
• A variable is a char variable when all its occurrences bind char occurrences in the previous
sense.
• A variable is an option variable when the overall expression can be matched without binding
this variable.
where the first argument is the continuation which captures the processing ocamllex would
usually perform (refilling the buffer, then calling the lexing function again), and the result type
that instantiates [’a] should unify with the result type of all lexing rules.
As an example, consider the following lexer that is parametrized over an arbitrary monad:
{
type token = EOL | INT of int | PLUS
(* Set up lexbuf *)
val on_refill : Lexing.lexbuf -> unit t
end)
= struct
refill {refill_handler}
| _
{ M.fail "unexpected character" }
{
end
}
produces OCaml 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 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.
%{
header
%}
declarations
%%
rules
%%
trailer
Comments are enclosed between /* and */ (as in C) in the “declarations” and “rules” sections,
and between (* and *) (as in OCaml) in the “header” and “trailer” sections.
298
15.4.2 Declarations
Declarations are given one per line. They all start with a % sign.
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
Chapter 15. Lexer and parser generators (ocamllex, ocamlyacc) 299
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.
The precedence declarations are used in the following way to resolve reduce/reduce and
shift/reduce conflicts:
• Tokens and rules have precedences. By default, the precedence of a rule is the precedence
of its rightmost terminal. You can override this default by using the %prec directive in
the rule.
• A reduce/reduce conflict is resolved in favor of the first rule (in the order given by the
source file), and ocamlyacc outputs a warning.
• A shift/reduce conflict is resolved by comparing the precedence of the rule to be reduced
with the precedence of the token to be shifted. If the precedence of the rule is higher,
then the rule will be reduced; if the precedence of the token is higher, then the token
will be shifted.
• A shift/reduce conflict between a rule and a token with the same precedence will be
resolved using the associativity: if the token is left-associative, then the parser will
reduce; if the token is right-associative, then the parser will shift. If the token is non-
associative, then the parser will declare a syntax error.
• When a shift/reduce conflict cannot be resolved using the above method, then ocamlyacc
will output a warning and the parser will always shift.
15.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 OCaml 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.
Nonterminal symbols are like regular OCaml symbols, except that they cannot end with '
(single quote).
300
15.5 Options
The ocamlyacc command recognizes the following options:
-bprefix
Name the output files prefix.ml, prefix.mli, prefix.output, instead of the default naming
convention.
-v Generate a description of the parsing tables and a report on conflicts resulting from ambigu-
ities in the grammar. The description is put in file grammar.output.
-version
Print version string and exit.
-vnum
Print short version number and exit.
- Read the grammar specification from standard input. The default output file names are
stdin.ml and stdin.mli.
– file
Process file as the grammar specification, even if its name starts with a dash (-) character.
This option must be the last on the command line.
At run-time, the ocamlyacc-generated parser can be debugged by setting the p option in the
OCAMLRUNPARAM environment variable (see section 13.2). This causes the pushdown automaton exe-
cuting the parser to print a trace of its action (tokens shifted, rules reduced, etc). The trace mentions
rule numbers and state numbers that can be interpreted by looking at the file grammar.output
generated by ocamlyacc -v.
Chapter 15. Lexer and parser generators (ocamllex, ocamlyacc) 301
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
The deterministic automata generated by ocamllex are limited to at most 32767 transitions.
The message above indicates that your lexer definition is too complex and overflows this
limit. This is commonly caused by lexer definitions that have separate rules for each of the
alphabetic keywords of the language, as in the following example.
To keep the generated automata small, rewrite those definitions with only one general “iden-
tifier” rule, followed by a hashtable lookup to separate keywords from identifiers:
[ "keyword1", KWD1;
"keyword2", KWD2; ...
"keyword100", KWD100 ]
}
rule token = parse
['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
{ try
Hashtbl.find keyword_table id
with Not_found ->
IDENT id }
The ocamldep command scans a set of OCaml 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:
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.
16.1 Options
The following command-line options are recognized by ocamldep.
-absname
Show absolute filenames in error messages.
-all
Generate dependencies on all required files, rather than assuming implicit dependencies.
-allow-approx
Allow falling back on a lexer-based approximation when parsing fails.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-as-map
For the following files, do not include delayed dependencies for module aliases. This option
305
306
assumes that they are compiled using options -no-alias-deps -w -49, and that those files
or their interface are passed with the -map option when computing dependencies for other
files. Note also that for dependencies to be correct in the implementation of a map file, its
interface should not coerce any of the aliases it contains.
-debug-map
Dump the delayed dependency map for each map file.
-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 from 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.
-nocwd
Do not add current working directory to the list of include directories.
-impl file
Process file as a .ml file.
-intf file
Process file as a .mli file.
-map file
Read and propagate the delayed dependencies for module aliases in file, so that the following
files will depend on the exported aliased modules if they use them. See the example below.
-ml-synonym .ext
Consider the given extension (with leading dot) to be a synonym for .ml.
-mli-synonym .ext
Consider the given extension (with leading dot) to be a synonym for .mli.
-modules
Output raw dependencies of the form
where Module1, . . . , ModuleN are the names of the compilation units referenced within the
file filename, but these names are not resolved to source file names. Such raw dependencies
cannot be used by make, but can be post-processed by other tools such as Omake.
-native
Generate dependencies for a pure native-code program (no bytecode version). When an
implementation file (.ml file) has no explicit interface file (.mli file), ocamldep generates
dependencies on the bytecode compiled file (.cmo file) to reflect interface changes. This can
cause unnecessary bytecode recompilations for programs that are compiled to native-code
Chapter 16. Dependency generator (ocamldep) 307
only. The flag -native causes dependencies on native compiled files (.cmx) to be generated
instead of on .cmo files. (This flag makes no difference if all source files have explicit .mli
interface files.)
-one-line
Output one line per file, regardless of the length.
-open module
Assume that module module is opened before parsing each of the following files.
-pp command
Cause ocamldep to call the given command as a preprocessor for each source file.
-ppx command
Pipe abstract syntax trees through preprocessor command.
-shared
Generate dependencies for native plugin files (.cmxs) in addition to native compiled files
(.cmx).
-slash
Under Windows, use a forward slash (/) as the path separator instead of the usual backward
slash (\). Under Unix, this option does nothing.
-sort
Sort files according to their dependencies.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-help or –help
Display a short usage summary and exit.
OCAMLC=ocamlc
OCAMLOPT=ocamlopt
OCAMLDEP=ocamldep
INCLUDES= # all relevant -I options here
OCAMLFLAGS=$(INCLUDES) # add other options for ocamlc here
OCAMLOPTFLAGS=$(INCLUDES) # add other options for ocamlopt here
prog1: $(PROG1_OBJS)
$(OCAMLC) -o prog1 $(OCAMLFLAGS) $(PROG1_OBJS)
prog2: $(PROG2_OBJS)
$(OCAMLOPT) -o prog2 $(OCAMLFLAGS) $(PROG2_OBJS)
# Common rules
%.cmo: %.ml
$(OCAMLC) $(OCAMLFLAGS) -c $<
%.cmi: %.mli
$(OCAMLC) $(OCAMLFLAGS) -c $<
%.cmx: %.ml
$(OCAMLOPT) $(OCAMLOPTFLAGS) -c $<
# Clean up
clean:
rm -f prog1 prog2
rm -f *.cm[iox]
# Dependencies
depend:
$(OCAMLDEP) $(INCLUDES) *.mli *.ml > .depend
include .depend
If you use module aliases to give shorter names to modules, you need to change the above
definitions. Assuming that your map file is called mylib.mli, here are minimal modifications.
OCAMLFLAGS=$(INCLUDES) -open Mylib
mylib.cmi: mylib.mli
$(OCAMLC) $(INCLUDES) -no-alias-deps -w -49 -c $<
Chapter 16. Dependency generator (ocamldep) 309
depend:
$(OCAMLDEP) $(INCLUDES) -map mylib.mli $(PROG1_OBJS:.cmo=.ml) > .depend
Note that in this case you should not compute dependencies for mylib.mli together with the
other files, hence the need to pass explicitly the list of files to process. If mylib.mli itself has
dependencies, you should compute them using -as-map.
310
Chapter 17
This chapter describes OCamldoc, a tool that generates documentation from special comments
embedded in source files. The comments used by OCamldoc are of the form (**. . . *) and follow
the format described in section 17.2.
OCamldoc can produce documentation in various formats: HTML, LATEX, TeXinfo, Unix man
pages, and dot dependency graphs. Moreover, users can add their own custom generators, as
explained in section 17.3.
In this chapter, we use the word element to refer to any of the following parts of an OCaml
source file: a type declaration, a value, a module, an exception, a module type, a type constructor,
a record field, a class, a class type, a class method, a class value or a class inheritance clause.
17.1 Usage
17.1.1 Invocation
OCamldoc is invoked via the command ocamldoc, as follows:
-html
Generate documentation in HTML default format. The generated HTML pages are stored in
the current directory, or in the directory specified with the -d option. You can customize the
style of the generated pages by editing the generated style.css file, or by providing your
own style sheet using option -css-style. The file style.css is not generated if it already
exists or if -css-style is used.
-latex
Generate documentation in LATEX default format. The generated LATEX document is saved in
311
312
file ocamldoc.out, or in the file specified with the -o option. The document uses the style
file ocamldoc.sty. This file is generated when using the -latex option, if it does not already
exist. You can change this file to customize the style of your LATEX documentation.
-texi
Generate documentation in TeXinfo default format. The generated LATEX document is saved
in file ocamldoc.out, or in the file specified with the -o option.
-man
Generate documentation as a set of Unix man pages. The generated pages are stored in the
current directory, or in the directory specified with the -d option.
-dot
Generate a dependency graph for the toplevel modules, in a format suitable for displaying
and processing by dot. The dot tool is available from https://graphviz.org/. The textual
representation of the graph is written to the file ocamldoc.out, or to the file specified with
the -o option. Use dot ocamldoc.out to display it.
-g file.cm[o,a,xs]
Dynamically load the given file, which defines a custom documentation generator. See section
17.4.1. This option is supported by the ocamldoc command (to load .cmo and .cma files)
and by its native-code version ocamldoc.opt (to load .cmxs files). If the given file is a simple
one and does not exist in the current directory, then ocamldoc looks for it in the custom
generators default directory, and in the directories specified with optional -i options.
-customdir
Display the custom generators default directory.
-i directory
Add the given directory to the path where to look for custom generators.
General options
-d dir
Generate files in directory dir, rather than the current directory.
-dump file
Dump collected information into file. This information can be read with the -load option in
a subsequent invocation of ocamldoc.
-hide modules
Hide the given complete module names in the generated documentation. modules is a list of
complete module names separated by ’,’, without blanks. For instance: Stdlib,M2.M3.
-inv-merge-ml-mli
Reverse the precedence of implementations and interfaces when merging. All elements in
implementation files are kept, and the -m option indicates which parts of the comments in
interface files are merged with the comments in implementation files.
Chapter 17. The documentation generator (ocamldoc) 313
-keep-code
Always keep the source code for values, methods and instance variables, when available.
-load file
Load information from file, which has been produced by ocamldoc -dump. Several -load
options can be given.
-m flags
Specify merge options between interfaces and implementations. (see section 17.1.2 for details).
flags can be one or several of the following characters:
d merge description
a merge @author
v merge @version
l merge @see
s merge @since
b merge @before
o merge @deprecated
p merge @param
e merge @raise
r merge @return
A merge everything
-no-custom-tags
Do not allow custom @-tags (see section 17.2.12).
-no-stop
Keep elements placed after/between the (**/**) special comment(s) (see section 17.2).
-o file
Output the generated documentation to file instead of ocamldoc.out. This option is mean-
ingful only in conjunction with the -latex, -texi, or -dot options.
-pp command
Pipe sources through preprocessor command.
-impl filename
Process the file filename as an implementation file, even if its extension is not .ml.
-intf filename
Process the file filename as an interface file, even if its extension is not .mli.
-text filename
Process the file filename as a text file, even if its extension is not .txt.
-sort
Sort the list of top-level modules before generating the documentation.
314
-stars
Remove blank characters until the first asterisk (’*’) in each line of comments.
-t title
Use title as the title for the generated documentation.
-intro file
Use content of file as ocamldoc text to use as introduction (HTML, LATEX and TeXinfo only).
For HTML, the file is used to create the whole index.html file.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-warn-error
Treat Ocamldoc warnings as errors.
-hide-warnings
Do not print OCamldoc warnings.
-help or –help
Display a short usage summary and exit.
Type-checking options
OCamldoc calls the OCaml type-checker to obtain type information. The following options impact
the type-checking phase. They have the same meaning as for the ocamlc and ocamlopt commands.
-I directory
Add directory to the list of directories search for compiled interface files (.cmi files).
-nolabels
Ignore non-optional labels in types.
-rectypes
Allow arbitrary recursive types. (See the -rectypes option to ocamlc.)
-all-params
Display the complete list of parameters for functions and methods.
-charset charset
Add information about character encoding being charset (default is iso-8859-1).
Chapter 17. The documentation generator (ocamldoc) 315
-colorize-code
Colorize the OCaml code enclosed in [ ] and {[ ]}, using colors to emphasize keywords,
etc. If the code fragments are not syntactically correct, no color is added.
-css-style filename
Use filename as the Cascading Style Sheet file.
-index-only
Generate only index files.
-short-functors
Use a short form to display functors:
is displayed as:
-latex-value-prefix prefix
Give a prefix to use for the labels of the values in the generated LATEX document. The
default prefix is the empty string. You can also use the options -latex-type-prefix,
-latex-exception-prefix, -latex-module-prefix, -latex-module-type-prefix,
-latex-class-prefix, -latex-class-type-prefix, -latex-attribute-prefix and
-latex-method-prefix.
These options are useful when you have, for example, a type and a value with the same name.
If you do not specify prefixes, LATEX will complain about multiply defined labels.
-latextitle n,style
Associate style number n to the given LATEX sectioning command style, e.g. section or
subsection. (LATEX only.) This is useful when including the generated document in another
LATEX document, at a given sectioning level. The default association is 1 for section, 2 for
subsection, 3 for subsubsection, 4 for paragraph and 5 for subparagraph.
-noheader
Suppress header in generated documentation.
-notoc
Do not generate a table of contents.
-notrailer
Suppress trailer in generated documentation.
-sepfiles
Generate one .tex file per toplevel module, instead of the global ocamldoc.out file.
316
-esc8
Escape accented characters in Info files.
-info-entry
Specify Info directory entry.
-info-section
Specify section of Info directory.
-noheader
Suppress header in generated documentation.
-noindex
Do not build index for Info files.
-notrailer
Suppress trailer in generated documentation.
-dot-colors colors
Specify the colors to use in the generated dot code. When generating module dependencies,
ocamldoc uses different colors for modules, depending on the directories in which they reside.
When generating types dependencies, ocamldoc uses different colors for types, depending on
the modules in which they are defined. colors is a list of color names separated by ’,’, as in
Red,Blue,Green. The available colors are the ones supported by the dot tool.
-dot-include-all
Include all modules in the dot output, not only modules given on the command line or loaded
with the -load option.
-dot-reduce
Perform a transitive reduction of the dependency graph before outputting the dot code. This
can be useful if there are a lot of transitive dependencies that clutter the graph.
-dot-types
Output dot code describing the type dependency graph instead of the module dependency
graph.
Chapter 17. The documentation generator (ocamldoc) 317
-man-mini
Generate man pages only for modules, module types, classes and class types, instead of pages
for all elements.
-man-suffix suffix
Set the suffix used for generated man filenames. Default is ’3o’, as in List.3o.
-man-section section
Set the section number used for generated man filenames. Default is ’3’.
• Only elements (values, types, classes, ...) declared in the .mli file are kept. In other terms,
definitions from the .ml file that are not exported in the .mli file are not documented.
• In a module, there must not be two modules, two module types or a module and a module
type with the same name. In the default HTML generator, modules ab and AB will be printed
to the same file on case insensitive file systems.
• In a module, there must not be two classes, two class types or a class and a class type with
the same name.
• In a module, there must not be two values, two types, or two exceptions with the same name.
• Values defined in tuple, as in let (x,y,z) = (1,2,3) are not kept by OCamldoc.
• There is no blank line or another special comment between the special comment and the ele-
ment. However, a regular comment can occur between the special comment and the element.
A special comment after an element is associated to this element if there is no blank line or
comment between the special comment and the element.
There are two exceptions: for constructors and record fields in type definitions, the associated
comment can only be placed after the constructor or field definition, without blank lines or other
comments between them. The special comment for a constructor with another constructor following
must be placed before the ’|’ character separating the two constructors.
The following sample interface file foo.mli illustrates the placement rules for comments in .mli
files.
(∗∗ The first special comment of the file is the comment associated
with the whole module.∗)
Chapter 17. The documentation generator (ocamldoc) 319
(∗∗ Special comments can be placed between elements and are kept
by the OCamldoc tool, but are not associated to any element.
@−tags in these comments are ignored.∗)
(∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗)
(∗∗ Comments like the one above, with more than two asterisks,
are ignored. ∗)
class my_class :
object
(∗∗ A comment to describe inheritance from cl ∗)
inherit cl
(∗∗ A special comment that is kept but not associated to any element ∗)
end
sig
(∗∗ The comment for value x. ∗)
val x : int
(∗ ... ∗)
end
end
(∗∗ This comment is not attached to any element since there is another
special comment just before the next element. ∗)
(∗∗/∗∗)
(∗∗ This value appears in the documentation, since the Stop special comment
in the class does not affect the parent module of the class.∗)
val foo : string
(∗∗/∗∗)
(∗∗ The value bar does not appear in the documentation.∗)
val bar : string
(∗∗/∗∗)
(∗∗ The type t appears since in the documentation since the previous stop comment
toggled off the "no documentation mode". ∗)
type t = string
The -no-stop option to ocamldoc causes the Stop special comments to be ignored.
Some elements support only a subset of all @-tags. Tags that are not relevant to the documented
element are simply ignored. For instance, all tags are ignored when documenting type constructors,
324
record fields, and class inheritance clauses. Similarly, a @param tag on a class instance variable is
ignored.
At last, (**) is the empty documentation comment.
text-element ::=
| inline-text-element
| blank-line force a new line.
inline-text-element ::=
| { {0 . . . 9}+ inline-text } format text as a section header; the integer following { in-
dicates the sectioning level.
| { {0 . . . 9}+ : label inline-text } same, but also associate the name label to the current point.
This point can be referenced by its fully-qualified label in a
{! command, just like any other element.
| {b inline-text } set text in bold.
| {i inline-text } set text in italic.
| {e inline-text } emphasize text.
| {C inline-text } center text.
| {L inline-text } left align text.
| {R inline-text } right align text.
| {ul list } build a list.
| {ol list } build an enumerated list.
| {{: string } inline-text } put a link to the given address (given as string) on the given
text.
| [ string ] set the given string in source code style.
| {[ string ]} set the given string in preformatted source code style.
| {v string v} set the given string in verbatim style.
| {% string %} target-specific content (LATEX code by default, see details in
17.2.10)
| {! string } insert a cross-reference to an element (see section 17.2.8 for
the syntax of cross-references).
| {!modules: string string... } insert an index table for the given module names. Used in
HTML only.
| {!indexlist} insert a table of links to the various indexes (types, values,
modules, ...). Used in HTML only.
| {^ inline-text } set text in superscript.
| {_ inline-text } set text in subscript.
| escaped-string typeset the given string as is; special characters (’{’, ’}’, ’[’,
’]’ and ’@’) must be escaped by a ’\’
326
is equivalent to:
The same shortcut is available for enumerated lists, using ’+’ instead of ’-’. Note that only one
list can be defined by this shortcut in nested lists.
In the case of variant constructors or record field, the constructor or field name should be
preceded by the name of the correspond type – to avoid the ambiguity of several types having the
same constructor names. For example, the constructor Node of the type tree will be referenced
as {!tree.Node} or {!const:tree.Node}, or possibly {!Mod1.Mod2.tree.Node} from outside the
module.
outside of the following text formatting : {ul list }, {ol list }, [ string ], {[ string ]}, {v string v},
{% string %}, {! string }, {^ text }, {_ text }.
@author string The author of the element. One author per @author tag.
There may be several @author tags for the same element.
@deprecated text The text should describe when the element was deprecated,
what to use as a replacement, and possibly the reason for
deprecation.
@param id text Associate the given description (text) to the given parameter
name id. This tag is used for functions, methods, classes and
functors.
@raise Exc text Explain that the element may raise the exception Exc.
@return text Describe the return value and its possible values. This tag
is used for functions and methods.
@see < URL > text Add a reference to the URL with the given text as comment.
@see 'filename' text Add a reference to the given file name (written between sin-
gle quotes), with the given text as comment.
@see "document-name" text Add a reference to the given document name (written be-
tween double quotes), with the given text as comment.
@since string Indicate when the element was introduced.
@before version text Associate the given description (text) to the given version
in order to document compatibility issues.
@version string The version number for the element.
This method will be called with the list of analysed and possibly merged Odoc_info.t_module
structures.
It is recommended to inherit from the current generator of the same kind as the one you want to
define. Doing so, it is possible to load various custom generators to combine improvements brought
by each one.
This is done using first class modules (see chapter 10.5).
The easiest way to define a custom generator is the following this example, here extending the
current HTML generator. We don’t have to know if this is the original HTML generator defined
in ocamldoc or if it has been extended already by a previously loaded custom generator :
(* ... *)
end
end;;
To know which methods to override and/or which methods are available, have a look at the
different base implementations, depending on the kind of generator you are extending :
For HTML
Here is how to develop a HTML generator handling your custom tags.
The class Odoc_html.Generator.html inherits from the class Odoc_html.info, containing a
field tag_functions which is a list pairs composed of a custom tag (e.g. "foo") and a function
taking a text and returning HTML code (of type string). To handle a new tag bar, extend the
current HTML generator and complete the tag_functions field:
(** Return HTML code for the given text of a bar tag. *)
method html_of_bar t = (* your code here *)
initializer
tag_functions <- ("bar", self#html_of_bar) :: tag_functions
end
end
let _ = Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor);;
Another method of the class Odoc_html.info will look for the function associated to a custom
tag and apply it to the text given to the tag. If no function is associated to a custom tag, then the
method prints a warning message on stderr.
Note: Existing command line options can be redefined using this function.
Options selecting a built-in generator to ocamldoc, such as -html, have no effect if a custom
generator of the same kind is provided using -g. If the kinds do not match, the selected built-in
generator is used and the custom one is ignored.
Unix:
The debugger is available on Unix systems that provide BSD sockets.
Windows:
The debugger is available under the Cygwin port of OCaml, but not under the native Win32
ports.
18.2 Invocation
18.2.1 Starting the debugger
The OCaml debugger is invoked by running the program ocamldebug with the name of the bytecode
executable file as first argument:
The arguments following program are optional, and are passed as command-line arguments to
the program being debugged. (See also the set arguments command.)
The following command-line options are recognized:
-c count
Set the maximum number of simultaneously live checkpoints to count.
333
334
-cd dir
Run the debugger program from the working directory dir, instead of the current directory.
(See also the cd command.)
-emacs
Tell the debugger it is executed under Emacs. (See section 18.10 for information on how to
run the debugger under Emacs.)
-I directory
Add directory to the list of directories searched for source files and compiled files. (See also
the directory command.)
-s socket
Use socket for communicating with the debugged program. See the description of the com-
mand set socket (section 18.8.8) for the format of socket.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-help or –help
Display a short usage summary and exit.
18.3 Commands
A debugger command is a single line of input. It starts with a command name, which is followed
by arguments depending on this name. Examples:
run
goto 1000
set arguments arg1 arg2
Chapter 18. The debugger (ocamldebug) 335
A command name can be truncated as long as there is no ambiguity. For instance, go 1000
is understood as goto 1000, since there are no other commands whose name starts with go. For
the most frequently used commands, ambiguous abbreviations are allowed. For instance, r stands
for run even though there are others commands starting with r. You can test the validity of an
abbreviation using the help command.
If the previous command has been successful, a blank line (typing just RET) will repeat it.
run Execute the program forward from current time. Stops at next breakpoint or when the
program terminates.
reverse
Execute the program backward from current time. Mostly useful to go to the last breakpoint
encountered before the current time.
step [count]
Run the program and stop at the next event. With an argument, do it count times. If count
is 0, run until the program terminates or a breakpoint is hit.
backstep [count]
Run the program backward and stop at the previous event. With an argument, do it count
times.
next [count]
Run the program and stop at the next event, skipping over function calls. With an argument,
do it count times.
previous [count]
Run the program backward and stop at the previous event, skipping over function calls. With
an argument, do it count times.
finish
Run the program until the current function returns.
start
Run the program backward and stop at the first event before the current function invocation.
goto time
Jump to the given time.
last [count]
Go back to the latest time recorded in the execution history. With an argument, do it count
times.
18.5 Breakpoints
A breakpoint causes the program to stop whenever a certain point in the program is reached. It
can be set in several ways using the break command. Breakpoints are assigned numbers when set,
for further reference. The most comfortable way to set breakpoints is through the Emacs interface
(see section 18.10).
break
Set a breakpoint at the current position in the program execution. The current position must
be on an event (i.e., neither at the beginning, nor at the end of the program).
break function
Set a breakpoint at the beginning of function. This works only when the functional value of
the identifier function has been computed and assigned to the identifier. Hence this command
cannot be used at the very beginning of the program execution, when all identifiers are still
undefined; use goto time to advance execution until the functional value is available.
delete [breakpoint-numbers]
Delete the specified breakpoints. Without argument, all breakpoints are deleted (after asking
for confirmation).
info breakpoints
Print the list of all breakpoints.
Chapter 18. The debugger (ocamldebug) 339
frame
Describe the currently selected stack frame.
frame frame-number
Select a stack frame by number and describe it. The frame currently executing when the
program stopped has number 0; its caller has number 1; and so on up the call stack.
up [count]
Select and display the stack frame just “above” the selected frame, that is, the frame that
called the selected frame. An argument says how many frames to go up.
down [count]
Select and display the stack frame just “below” the selected frame, that is, the frame that
was called by the selected frame. An argument says how many frames to go down.
grammar:
simple-expr ::= lowercase-ident
| {capitalized-ident .} lowercase-ident
| *
| $ integer
| simple-expr . lowercase-ident
| simple-expr .( integer )
| simple-expr .[ integer ]
| ! simple-expr
| ( simple-expr )
The first two cases refer to a value identifier, either unqualified or qualified by the path to the
structure that define it. * refers to the result just computed (typically, the value of a function
application), and is valid only if the selected event is an “after” event (typically, a function appli-
cation). $ integer refer to a previously printed value. The remaining four forms select part of an
expression: respectively, a record field, an array element, a string element, and the current contents
of a reference.
print variables
Print the values of the given variables. print can be abbreviated as p.
display variables
Same as print, but limit the depth of printing to 1. Useful to browse large data structures
without printing them in full. display can be abbreviated as d.
When printing a complex expression, a name of the form $integer is automatically assigned to
its value. Such names are also assigned to parts of the value that cannot be printed because the
maximal printing depth is exceeded. Named values can be printed later on with the commands
p $integer or d $integer. Named values are valid only as long as the program is stopped. They are
forgotten as soon as the program resumes execution.
set print_depth d
Limit the printing of values to a maximal depth of d.
set print_length l
Limit the printing of values to at most l nodes printed.
A shell is used to pass the arguments to the debugged program. You can therefore use
wildcards, shell variables, and file redirections inside the arguments. To debug programs
that read from standard input, it is recommended to redirect their input from a file (using
set arguments < input-file), otherwise input to the program and input to the debugger
are not properly separated, and inputs are not properly replayed when running the program
backwards.
directory directorynames
Add the given directories to the search path. These directories are added at the front, and
will therefore be searched first.
directory
Reset the search path. This requires confirmation.
cd directory
Set the working directory for ocamldebug to directory.
On the debugged program side, the socket name is passed through the CAML_DEBUG_SOCKET
environment variable.
Chapter 18. The debugger (ocamldebug) 343
As checkpointing is quite expensive, it must not be done too often. On the other hand, backward
execution is faster when checkpoints are taken more often. In particular, backward single-stepping
is more responsive when many checkpoints have been taken just before the current time. To fine-
tune the checkpointing strategy, the debugger does not take checkpoints at the same frequency
for long displacements (e.g. run) and small ones (e.g. step). The two variables bigstep and
smallstep contain the number of events between two checkpoints in each case.
info checkpoints
Print a list of checkpoints.
load_printer "file-name"
Load in the debugger the indicated .cmo or .cma object file. The file is loaded in an environ-
ment consisting only of the OCaml standard library plus the definitions provided by object
files previously loaded using load_printer. If this file depends on other object files not yet
loaded, the debugger automatically loads them if it is able to find them in the search path.
The loaded file does not have direct access to the modules of the program being debugged.
install_printer printer-name
Register 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 debugger will call printer-name when it
has such an object to print. The printing function printer-name must use the Format library
344
module to produce its output, otherwise its output will not be correctly located in the values
printed by the toplevel loop.
The value path printer-name must refer to one of the functions defined by the object files
loaded using load_printer. It cannot reference the functions of the program being debugged.
remove_printer printer-name
Remove the named function from the table of value printers.
source filename
Read debugger commands from the script filename.
C-c C-s
(command step): execute the program one step forward.
C-c C-k
(command backstep): execute the program one step backward.
C-c C-n
(command next): execute the program one step forward, skipping over function calls.
C-c C-p
(command print): print value of identifier at point.
Chapter 18. The debugger (ocamldebug) 345
C-c C-d
(command display): display value of identifier at point.
C-c C-r
(command run): execute the program forward to next breakpoint.
C-c C-v
(command reverse): execute the program backward to latest breakpoint.
C-c C-l
(command last): go back one step in the command history.
C-c C-t
(command backtrace): display backtrace of function calls.
C-c C-f
(command finish): run forward till the current function returns.
C-c <
(command up): select the stack frame below the current frame.
C-c >
(command down): select the stack frame above the current frame.
In all buffers in OCaml editing mode, the following debugger commands are also available:
Profiling (ocamlprof)
This chapter describes how the execution of OCaml programs can be profiled, by recording how
many times functions are called, branches of conditionals are taken, . . .
Note If a module (.ml file) doesn’t have a corresponding interface (.mli file), then compiling
it with ocamlcp will produce object files (.cmi and .cmo) that are not compatible with the ones
produced by ocamlc, which may lead to problems (if the .cmi or .cmo is still around) when switching
between profiling and non-profiling compilations. To avoid this problem, you should always have a
.mli file for each .ml file. The same problem exists with ocamloptp.
Note To make sure your programs can be compiled in profiling mode, avoid using any identifier
that begins with __ocaml_prof.
The amount of profiling information can be controlled through the -P option to ocamlcp or
ocamloptp, 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 each function body
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
347
348
t try . . . with . . . branches: a count point is set at the beginning of the body of each branch
For instance, compiling with ocamlcp -P film profiles function calls, if. . . then. . . else. . . , loops
and pattern matching.
Calling ocamlcp or ocamloptp without the -P option defaults to -P fm, meaning that only
function calls and pattern matching are profiled.
Note For compatibility with previous releases, ocamlcp also accepts the -p option, with the
same arguments and behaviour as -P.
The ocamlcp and ocamloptp commands also accept all the options of the corresponding ocamlc
or ocamlopt compiler, except the -pp (preprocessing) option.
-args filename
Read additional newline-terminated command line arguments from filename.
-args0 filename
Read additional null character terminated command line arguments from filename.
-f dumpfile
Specifies an alternate dump file of profiling information to be read.
Chapter 19. Profiling (ocamlprof) 349
-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 (* sn *).
-impl filename
Process the file filename as an implementation file, even if its extension is not .ml.
-intf filename
Process the file filename as an interface file, even if its extension is not .mli.
-version
Print version string and exit.
-vnum
Print short version number and exit.
-help or –help
Display a short usage summary and exit.
This chapter describes how user-defined primitives, written in C, can be linked with OCaml code
and called from OCaml functions, and how these C functions can call back to OCaml code.
User primitives are declared in an implementation file or struct . . . end module expression using
the external keyword:
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 seek_in primitive is declared in the standard library
module Stdlib:
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
351
352
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 OCaml function. On the other hand, it should
not be used in library modules if they have side-effects at toplevel, as this direct call interferes with
the linker’s algorithm for removing unused modules from libraries at link-time.
The arity (number of arguments) of a primitive is automatically determined from its OCaml
type in the external declaration, by counting the number of function arrows in the type. For
instance, seek_in above has arity 2, and the caml_ml_seek_in C function is called with two
arguments. Similarly,
has arity 1, and the caml_ml_seek_in_pair C function receives one argument (which is a pair
of OCaml values).
Type abbreviations are not expanded when determining the arity of a primitive. For instance,
f has arity 1, but g has arity 2. This allows a primitive to return a functional value (as in the
f example above): just remember to name the functional return type in a type abbreviation.
The language accepts external declarations with one or two flag strings in addition to the C
function’s name. These flags are reserved for the implementation of the standard library.
CAMLprim value input(value channel, value buffer, value offset, value length)
{
...
}
When the primitive function is applied in an OCaml 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 OCaml 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 OCaml 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:
Chapter 20. Interfacing C with OCaml 353
The names of the two C functions must be given in the primitive declaration, as follows:
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 OCaml values, and encoding the return value as an
OCaml 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 OCaml values to C values, call
the first function, and convert the returned C value to OCaml value. For instance, here is the stub
code for the input primitive:
CAMLprim value input(value channel, value buffer, value offset, value 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 CAMLprim macro expands to the required compiler directives to ensure that
the function is exported and accessible from OCaml.) The hard work is performed by the function
getblock, which is declared as:
To write C code that operates on OCaml values, the following include files are provided:
Before including any of these files, you should define the CAML_NAME_SPACE macro. For instance,
#define CAML_NAME_SPACE
#include "caml/mlvalues.h"
#include "caml/fail.h"
These files reside in the caml/ subdirectory of the OCaml standard library directory, which is
returned by the command ocamlc -where (usually /usr/local/lib/ocaml or /usr/lib/ocaml).
Note: Including the header files without first defining CAML_NAME_SPACE introduces in scope
short names for most functions. Those short names are deprecated, and may be removed in the
future because they usually produce clashes with names defined by other C libraries.
• 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 OCaml linker,
that provide implementations for the user’s primitives.
Chapter 20. Interfacing C with OCaml 355
This builds a runtime system with the required primitives. The OCaml linker 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 names of the desired OCaml object files (.cmo and .cma files) ;
• the names of the C object files and libraries (.o and .a files) that implement the required
primitives. Under Unix and Windows, a library named libname.a (respectively, .lib) re-
siding in one of the standard library directories can also be specified as -cclib -lname.
If you are using the native-code compiler ocamlopt, the -custom flag is not needed, as the
final linking phase of ocamlopt always builds a standalone executable. To build a mixed OCaml/C
executable, execute the ocamlopt command with:
• the names of the desired OCaml native object files (.cmx and .cmxa files);
• the names of the C object files and libraries (.o, .a, .so or .dll files) that implement the
required primitives.
Starting with Objective Caml 3.00, it is possible to record the -custom option as well as the
names of C libraries in an OCaml library file .cma or .cmxa. For instance, consider an OCaml
library mylib.cma, built from the OCaml object files a.cmo and b.cmo, which reference C code in
libmylib.a. If the library is built as follows:
and the system will automatically add the -custom and -cclib -lmylib options, achieving the
same effect as
and then ask users to provide the -custom and -cclib -lmylib options themselves at link-time:
The former alternative is more convenient for the final users of the library, however.
356
• the names of the desired OCaml object files (.cmo and .cma files) ;
• the names of the C shared libraries (.so or .dll files) that implement the required primitives.
Under Unix and Windows, a library named dllname.so (respectively, .dll) residing in one
of the standard library directories can also be specified as -dllib -lname.
Do not set the -custom flag, otherwise you’re back to static linking as described in section 20.1.3.
The ocamlmklib tool (see section 20.14) automates steps 2 and 3.
As in the case of static linking, it is possible (and recommended) to record the names of C
libraries in an OCaml .cma library archive. Consider again an OCaml library mylib.cma, built
from the OCaml object files a.cmo and b.cmo, which reference C code in dllmylib.so. If the
library is built as follows:
and the system will automatically add the -dllib -lmylib option, achieving the same effect
as
Using this mechanism, users of the library mylib.cma do not need to known that it references
C code, nor whether this C code must be statically linked (using -custom) or dynamically linked.
libraries are available on all these platforms. In contrast, executables generated by ocamlc -custom
run only on the platform on which they were created, because they embark a custom-tailored run-
time system specific to that platform. In addition, dynamic linking results in smaller executables.
Another advantage of dynamic linking is that the final users of the library do not need to have
a C compiler, C linker, and C runtime libraries installed on their machines. This is no big deal
under Unix and Cygwin, but many Windows users are reluctant to install Microsoft Visual C just
to be able to do ocamlc -custom.
There are two drawbacks to dynamic linking. The first is that the resulting executable is not
stand-alone: it requires the shared libraries, as well as ocamlrun, to be installed on the machine
executing the code. If you wish to distribute a stand-alone executable, it is better to link it stat-
ically, using ocamlc -custom -ccopt -static or ocamlopt -ccopt -static. Dynamic linking
also raises the “DLL hell” problem: some care must be taken to ensure that the right versions of
the shared libraries are found at start-up time.
The second drawback of dynamic linking is that it complicates the construction of the library.
The C compiler and linker flags to compile to position-independent code and build a shared library
vary wildly between different Unix systems. Also, dynamic linking is not supported on all Unix
systems, requiring a fall-back case to static linking in the Makefile for the library. The ocamlmklib
command (see section 20.14) tries to hide some of these system dependencies.
In conclusion: dynamic linking is highly recommended under the native Windows port, because
there are no portability problems and it is much more convenient for the end users. Under Unix,
dynamic linking should be considered for mature, frequently used libraries because it enhances
platform-independence of bytecode executables. For new or rarely-used libraries, static linking is
much simpler to set up in a portable way.
The bytecode executable myprog can then be launched as usual: myprog args or
/home/me/ocamlunixrun myprog args.
358
Notice that the bytecode libraries unix.cma and threads.cma must be given twice: when
building the runtime system (so that ocamlc knows which C primitives are required) and also
when building the bytecode executable (so that the bytecode from unix.cma and threads.cma is
actually linked in).
• an unboxed integer;
• or a pointer to a block inside the heap, allocated through one of the caml_alloc_* functions
described in section 20.4.4.
20.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 benefit 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:
• The default representation. In the present version of OCaml, the default is the boxed repre-
sentation.
Chapter 20. Interfacing C with OCaml 361
20.3.3 Arrays
Arrays of integers and pointers are represented like tuples, that is, as pointers to blocks tagged 0.
They are accessed with the Field macro for reading and the caml_modify function for writing.
Arrays of floating-point numbers (type float array) have a special, unboxed, more efficient
representation. 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.
type t =
| A (* First constant constructor -> integer "Val_int(0)" *)
| B of string (* First non-constant constructor -> block with tag 0 *)
| C (* Second constant constructor -> integer "Val_int(1)" *)
| D of bool (* Second non-constant constructor -> block with tag 1 *)
| E of t * t (* Third non-constant constructor -> block with tag 2 *)
As an optimization, unboxable concrete data types are represented specially; a concrete data
type is unboxable if it has exactly one constructor and this constructor has exactly one argument.
Unboxable concrete data types are represented in the same ways as unboxable record types: see
the description in section 20.3.2.
20.3.5 Objects
Objects are represented as blocks with tag Object_tag. The first field of the block refers to the
object’s class and associated method suite, in a format that cannot easily be exploited from C. The
second field contains a unique object ID, used for comparisons. The remaining fields of the object
362
contain the values of the instance variables of the object. It is unsafe to access directly instance
variables, as the type system provides no guarantee about the instance variables contained by an
object.
One may extract a public method from an object using the C function caml_get_public_method
(declared in <caml/mlvalues.h>.) Since public method tags are hashed in the same way as variant
tags, and methods are functions taking self as first argument, if you want to do the method call
foo#bar from the C side, you should call:
• Is_some(v) is true if value v (assumed to be of option type) corresponds to the Some con-
structor.
• Val_bool(x) returns the OCaml boolean representing the truth value of the C integer x.
• 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.
• Store_field(b, n, v) stores the value v in the field number n of value b, which must be a
structured block.
• caml_string_length(v) returns the length (number of bytes) of the string or byte sequence
v.
• Byte(v, n) returns the nþ byte of the string or byte sequence v, with type char. Bytes are
numbered from 0 to string_length(v) − 1.
• Byte_u(v, n) returns the nþ byte of the string or byte sequence v, with type unsigned char.
Bytes 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 * or, when
OCaml is configured with -force-safe-string, with type const char *. This pointer is a
valid C string: there is a null byte after the last byte in the string. However, OCaml strings
can contain embedded null bytes, which will confuse the usual C functions over strings.
• Bytes_val(v) returns a pointer to the first byte of the byte sequence v, with type
unsigned char *.
• Double_val(v) returns the floating-point number contained in value v, with type double.
• Data_custom_val(v) returns a pointer to the data part of the custom block v. This pointer
has type void * and must be cast to the type of the data contained in the custom block.
• caml_field_unboxed(v) returns the value of the field of a value v of any unboxed type (record
or concrete data type).
• caml_field_boxed(v) returns the value of the field of a value v of any boxed type (record or
concrete data type).
The expressions Field(v, n), Byte(v, n) and Byte_u(v, n) 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).
• caml_alloc(n, t) returns a fresh block of size n with tag t. If t is less than No_scan_tag,
then the fields of the block are initialized with a valid value in order to satisfy the GC
constraints.
• caml_alloc_string(n) returns a byte sequence (or string) value of length n bytes. The
sequence initially contains uninitialized bytes.
• caml_copy_string(s) returns a string or byte sequence value containing a copy of the null-
terminated C string s (a char *).
the successive calls to f. (This function must not be used to build an array of floating-point
numbers.)
• caml_alloc_unboxed(v) returns the value (of any unboxed type) whose field is the value v.
• caml_alloc_boxed(v) allocates and returns a value (of any boxed type) whose field is the
value v.
• caml_alloc_shr(n, t) returns a fresh block of size n, with tag t. The size of the block
can be greater than Max_young_wosize. (It can also be smaller, but in this case it is more
efficient to call caml_alloc_small instead of caml_alloc_shr.) If this block is a structured
block (i.e. if t < No_scan_tag), then the fields of the block (initially containing garbage)
must be initialized with legal values (using the caml_initialize function described below)
before the next allocation.
• caml_failwith(s), where s is a null-terminated C string (with type char *), raises exception
Failure with argument s.
366
Raising arbitrary exceptions from C is more delicate: the exception identifier is dynamically
allocated by the OCaml program, and therefore must be communicated to the C function using the
registration facility described below in section 20.7.3. Once the exception identifier is recovered in
C, the following functions actually raise the exception:
Rule 1 A function that has parameters or local variables of type value must begin with a call to
one of the CAMLparam macros and return with CAMLreturn, CAMLreturn0, or CAMLreturnT. In
particular, CAMLlocal and CAMLxparam can only be called after CAMLparam.
There are six CAMLparam macros: CAMLparam0 to CAMLparam5, which take zero to five arguments
respectively. If your function has no more than 5 parameters of type value, use the corresponding
macros with these parameters as arguments. If your function has more than 5 parameters of type
value, use CAMLparam5 with five of these parameters, and use one or more calls to the CAMLxparam
macros for the remaining parameters (CAMLxparam1 to CAMLxparam5).
The macros CAMLreturn, CAMLreturn0, and CAMLreturnT are used to replace the C keyword
return. Every occurrence of return x must be replaced by CAMLreturn (x) if x has type value,
or CAMLreturnT (t, x) (where t is the type of x); every occurrence of return without argument
must be replaced by CAMLreturn0. If your C function is a procedure (i.e. if it returns void), you
must insert CAMLreturn0 at the end (to replace C’s implicit return).
Note: some C compilers give bogus warnings about unused variables caml__dummy_xxx at each
use of CAMLparam and CAMLlocal. You should ignore them.
Chapter 20. Interfacing C with OCaml 367
Example:
Note: if your function is a primitive with more than 5 arguments for use with the byte-code
runtime, its arguments are not values and must not be declared (they have types value * and
int).
Rule 2 Local variables of type value must be declared with one of the CAMLlocal macros. Arrays of
values are declared with CAMLlocalN. These macros must be used at the beginning of the function,
not in a nested block.
The macros CAMLlocal1 to CAMLlocal5 declare and initialize one to five local variables of type
value. The variable names are given as arguments to the macros. CAMLlocalN(x, n) declares and
initializes a local variable of type value [n]. You can use several calls to these macros if you have
more than 5 local variables.
Example:
Rule 3 Assignments to the fields of structured blocks must be done with the Store_field macro
(for normal blocks) or Store_double_field macro (for arrays and records of floating-point num-
bers). Other assignments must not use Store_field nor Store_double_field.
Store_field (b, n, v) stores the value v in the field number n of value b, which must be a
block (i.e. Is_block(b) must be true).
Example:
Use with CAMLlocalN: Arrays of values declared using CAMLlocalN must not be written to
using Store_field. Use the normal C array syntax instead.
Rule 4 Global variables containing values must be registered with the garbage collector using the
caml_register_global_root function, save that global variables and locations that will only ever
contain OCaml integers (and never pointers) do not have to be registered.
The same is true for any memory location outside the OCaml heap that contains a value and is
not guaranteed to be reachable—for as long as it contains such value—from either another registered
global variable or location, local variable declared with CAMLlocal or function parameter declared
with CAMLparam.
Note: The CAML macros use identifiers (local variables, type identifiers, structure tags) that start
with caml__. Do not use any identifier starting with caml__ in your programs.
Chapter 20. Interfacing C with OCaml 369
Rule 5 After a structured block (a block with tag less than No_scan_tag) is allocated with the
low-level functions, all fields of this block must be filled with well-formed values before the next
allocation operation. If the block has been allocated with caml_alloc_small, filling is performed by
direct assignment to the fields of the block:
Field(v, n) = vn ;
If the block has been allocated with caml_alloc_shr, filling is performed through the
caml_initialize function:
caml_initialize(&Field(v, n), vn );
The next allocation can trigger a garbage collection. The garbage collector assumes that all
structured blocks contain well-formed values. Newly created blocks contain random data, which
generally do not represent well-formed values.
If you really need to allocate before the fields can receive their final value, first initialize with
a constant value (e.g. Val_unit), then allocate, then modify the fields with the correct value (see
rule 6).
Field(v, n) = w;
is safe only if v is a block newly allocated by caml_alloc_small; that is, if no allocation took
place between the allocation of v and the assignment to the field. In all other cases, never assign
directly. If the block has just been allocated by caml_alloc_shr, use caml_initialize to assign a
value to a field for the first time:
Otherwise, you are updating a field that previously contained a well-formed value; then, call the
caml_modify function:
To illustrate the rules above, here is a C function that builds and returns a list containing the
two integers given as parameters. First, we write it using the simplified allocation functions:
Here, the registering of result is not strictly needed, because no allocation takes place after
it gets its value, but it’s easier and safer to simply register all the local variables that have type
value.
Here is the same function written using the low-level allocation functions. We notice that
the cons cells are small blocks and can be allocated with caml_alloc_small, and filled by direct
assignments on their fields.
In the two examples above, the list is built bottom-up. Here is an alternate way, that proceeds
top-down. It is less efficient, but illustrates the use of caml_modify.
It would be incorrect to perform Field(r, 1) = tail directly, because the allocation of tail
has taken place since r was allocated.
ocamlc -c curses.ml
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_stubs.c, looks like this:
CAMLprim value caml_curses_newwin(value nlines, value ncols, value x0, value y0)
{
CAMLparam4 (nlines, ncols, x0, y0);
CAMLreturn (alloc_window(newwin(Int_val(nlines), Int_val(ncols),
Int_val(x0), Int_val(y0))));
}
addstr(String_val(s));
CAMLreturn (Val_unit);
}
ocamlc -c curses_stubs.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 OCaml program prog.ml that uses the curses module:
(On some machines, you may need to put -cclib -lcurses -cclib -ltermcap or
-cclib -ltermcap instead of -cclib -lcurses.)
The C code can then recover the exception identifier using caml_named_value and pass it as first
argument to the functions raise_constant, raise_with_arg, and raise_with_string (described
in section 20.4.7) to actually raise the exception. For example, here is a C function that raises the
Error exception with the given argument:
• The C part of the program must provide a main function, which will override the default main
function provided by the OCaml runtime system. Execution will start in the user-defined main
function just like for a regular C program.
• At some point, the C code must call caml_main(argv) to initialize the OCaml code. The
argv argument is a C array of strings (type char **), terminated with a NULL pointer, which
represents the command-line arguments, as passed as second argument to main. The OCaml
array Sys.argv will be initialized from this parameter. For the bytecode compiler, argv[0]
and argv[1] are also consulted to find the file containing the bytecode.
• The call to caml_main initializes the OCaml runtime system, loads the bytecode (in the case
of the bytecode compiler), and executes the initialization code of the OCaml program. Typi-
cally, this initialization code registers callback functions using Callback.register. Once the
OCaml initialization code is complete, control returns to the C code that called caml_main.
• The C code can then invoke OCaml functions using the callback mechanism (see
section 20.7.1).
linking step must be performed by ocamlc. Second, the OCaml runtime library must be able to find
the name of the executable file from the command-line arguments. When using caml_main(argv)
as in section 20.7.4, this means that argv[0] or argv[1] must contain the executable file name.
An alternative is to embed the bytecode in the C code. The -output-obj and
-output-complete-obj options to ocamlc are provided for this purpose. They cause the ocamlc
compiler to output a C object file (.o file, .obj under Windows) containing the bytecode for the
OCaml part of the program, as well as a caml_startup function. The C object file produced by
ocamlc -output-complete-obj also contains the runtime and autolink libraries. The C object
file produced by ocamlc -output-obj or ocamlc -output-complete-obj can then be linked with
C code using the standard C compiler, or stored in a C library.
The caml_startup function must be called from the main C program in order to initialize the
OCaml runtime and execute the OCaml initialization code. Just like caml_main, it takes one argv
parameter containing the command-line parameters. Unlike caml_main, this argv parameter is
used only to initialize Sys.argv, but not for finding the name of the executable file.
The caml_startup function calls the uncaught exception handler (or enters the debugger, if
running under ocamldebug) if an exception escapes from a top-level module initialiser. Such ex-
ceptions may be caught in the C code by instead using the caml_startup_exn function and testing
the result using Is_exception_result (followed by Extract_exception if appropriate).
The -output-obj and -output-complete-obj options can also be used to obtain the C
source file. More interestingly, these options can also produce directly a shared library (.so
file, .dll under Windows) that contains the OCaml code, the OCaml runtime system and any
other static C code given to ocamlc (.o, .a, respectively, .obj, .lib). This use of -output-obj
and -output-complete-obj is very similar to a normal linking step, but instead of producing
a main program that automatically runs the OCaml code, it produces a shared library that
can run the OCaml code on demand. The three possible behaviors of -output-obj and
-output-complete-obj (to produce a C source code .c, a C object file .o, a shared library .so),
are selected according to the extension of the resulting file (given with -o).
The native-code compiler ocamlopt also supports the -output-obj and -output-complete-obj
options, causing it to output a C object file or a shared library containing the native code for
all OCaml modules on the command-line, as well as the OCaml startup code. Initialization is
performed by calling caml_startup (or caml_startup_exn) as in the case of the bytecode compiler.
The file produced by ocamlopt -output-complete-obj also contains the runtime and autolink
libraries.
For the final linking phase, in addition to the object file produced by -output-obj, you will have
to provide the OCaml runtime library (libcamlrun.a for bytecode, libasmrun.a for native-code),
as well as all C libraries that are required by the OCaml libraries used. For instance, assume the
OCaml part of your program uses the Unix library. With ocamlc, you should do:
ocamlc -output-obj -o camlcode.o unix.cma other .cmo and .cma files
cc -o myprog C objects and libraries \
camlcode.o -L‘ocamlc -where‘ -lunix -lcamlrun
With ocamlopt, you should do:
ocamlopt -output-obj -o camlcode.o unix.cmxa other .cmx and .cmxa files
cc -o myprog C objects and libraries \
camlcode.o -L‘ocamlc -where‘ -lunix -lasmrun
Chapter 20. Interfacing C with OCaml 379
For the final linking phase, in addition to the object file produced by -output-complete-obj,
you will have only to provide the C libraries required by the OCaml runtime.
For instance, assume the OCaml part of your program uses the Unix library. With ocamlc, you
should do:
ocamlc -output-complete-obj -o camlcode.o unix.cma other .cmo and .cma files
cc -o myprog C objects and libraries \
camlcode.o C libraries required by the runtime, eg -lm -ldl -lcurses -lpthread
With ocamlopt, you should do:
ocamlopt -output-complete-obj -o camlcode.o unix.cmxa other .cmx and .cmxa files
cc -o myprog C objects and libraries \
camlcode.o C libraries required by the runtime, eg -lm -ldl
Warning: On some ports, special options are required on the final linking phase that links
together the object file produced by the -output-obj and -output-complete-obj options and the
remainder of the program. Those options are shown in the configuration file Makefile.config
generated during compilation of OCaml, as the variable OC_LDFLAGS.
• Windows with the MSVC compiler: the object file produced by OCaml have been compiled
with the /MD flag, and therefore all other object files linked with it should also be compiled
with /MD.
• other systems: you may have to add one or more of -lcurses, -lm, -ldl, depending on your
OS and C compiler.
• Triggering finalization of allocated custom blocks (see section 20.9). For example,
Stdlib.in_channel and Stdlib.out_channel are represented by custom blocks that
enclose file descriptors, which are to be released.
380
• Unloading the dependent shared libraries that were loaded by the runtime, including dynlink
plugins.
• Freeing the memory blocks that were allocated by the runtime with malloc. Inside C prim-
itives, it is advised to use caml_stat_* functions from memory.h for managing static (that
is, non-moving) blocks of heap memory, as all the blocks allocated with these functions are
automatically freed by caml_shutdown. For ensuring compatibility with legacy C stubs that
have used caml_stat_* incorrectly, this behaviour is only enabled if the runtime is started
with a specialized caml_startup_pooled function.
As a shared library may have several clients simultaneously, it is made for convenience that
caml_startup (and caml_startup_pooled) may be called multiple times, given that each such
call is paired with a corresponding call to caml_shutdown (in a nested fashion). The runtime will
be unloaded once there are no outstanding calls to caml_startup.
Once a runtime is unloaded, it cannot be started up again without reloading the shared library
and reinitializing its static data. Therefore, at the moment, the facility is only useful for building
reloadable shared libraries.
#include <stdio.h>
#include <string.h>
#include <caml/mlvalues.h>
#include <caml/callback.h>
int fib(int n)
{
Chapter 20. Interfacing C with OCaml 381
char * format_result(int n)
{
static const value * format_result_closure = NULL;
if (format_result_closure == NULL)
format_result_closure = caml_named_value("format_result");
return strdup(String_val(caml_callback(*format_result_closure, Val_int(n))));
/* We copy the C string returned by String_val to the C heap
so that it remains valid after garbage collection. */
}
We now compile the OCaml code to a C object file and put it in a C library along with the
stub code in modwrap.c and the OCaml runtime system:
(One can also use ocamlopt -output-obj instead of ocamlc -custom -output-obj. In this
case, replace libcamlrun.a (the bytecode runtime library) by libasmrun.a (the native-code run-
time library).)
Now, we can use the two functions fib and format_result in any C program, just like regular
C functions. Just remember to call caml_startup (or caml_startup_exn) once before.
#include <stdio.h>
#include <caml/callback.h>
return 0;
}
(On some machines, you may need to put -ltermcap or -lcurses -ltermcap instead of
-lcurses.)
• char *identifier
A zero-terminated character string serving as an identifier for serialization and deserialization
operations.
• void (*finalize)(value v)
The finalize field contains a pointer to a C function that is called when the block becomes
unreachable and is about to be reclaimed. The block is passed as first argument to the
function. The finalize field can also be custom_finalize_default to indicate that no
finalization function is associated with the block.
• intnat (*hash)(value v)
The hash field contains a pointer to a C function that is called whenever OCaml’s generic
hash operator (see module Hashtbl[25.22]) is applied to a custom block. The C function can
return an arbitrary integer representing the hash value of the data contained in the given
custom block. The hash value must be compatible with the compare function, in the sense
that two structurally equal data (that is, two custom blocks for which compare returns 0)
must have the same hash value.
The hash field can be set to custom_hash_default, in which case the custom block is ignored
during hash computation.
Note: the finalize, compare, hash, serialize and deserialize functions attached to custom
block descriptors must never trigger a garbage collection. Within these functions, do not call any
of the OCaml allocation functions, and do not perform a callback into OCaml code. Do not use
CAMLparam to register the parameters to these functions, and do not use CAMLreturn to return the
result.
Use this function when your custom block holds only out-of-heap memory (memory allocated with
malloc or caml_stat_alloc) and no other resources. used should be the number of bytes of out-
of-heap memory that are held by your custom block. This function works like caml_alloc_custom
except that the max parameter is under the control of the user (via the custom_major_ratio,
Chapter 20. Interfacing C with OCaml 385
Function Action
caml_serialize_int_1 Write a 1-byte integer
caml_serialize_int_2 Write a 2-byte integer
caml_serialize_int_4 Write a 4-byte integer
caml_serialize_int_8 Write a 8-byte integer
caml_serialize_float_4 Write a 4-byte float
caml_serialize_float_8 Write a 8-byte float
caml_serialize_block_1 Write an array of 1-byte quantities
caml_serialize_block_2 Write an array of 2-byte quantities
caml_serialize_block_4 Write an array of 4-byte quantities
caml_serialize_block_8 Write an array of 8-byte quantities
caml_deserialize_uint_1 Read an unsigned 1-byte integer
caml_deserialize_sint_1 Read a signed 1-byte integer
caml_deserialize_uint_2 Read an unsigned 2-byte integer
caml_deserialize_sint_2 Read a signed 2-byte integer
caml_deserialize_uint_4 Read an unsigned 4-byte integer
caml_deserialize_sint_4 Read a signed 4-byte integer
caml_deserialize_uint_8 Read an unsigned 8-byte integer
caml_deserialize_sint_8 Read a signed 8-byte integer
caml_deserialize_float_4 Read a 4-byte float
caml_deserialize_float_8 Read an 8-byte float
caml_deserialize_block_1 Read an array of 1-byte quantities
caml_deserialize_block_2 Read an array of 2-byte quantities
caml_deserialize_block_4 Read an array of 4-byte quantities
caml_deserialize_block_8 Read an array of 8-byte quantities
caml_deserialize_error Signal an error during deserialization; input_value or
Marshal.from_... raise a Failure exception after clean-
ing up their internal data structures
Serialization functions are attached to the custom blocks to which they apply. Obviously, dese-
rialization functions cannot be attached this way, since the custom block does not exist yet when de-
serialization begins! Thus, the struct custom_operations that contain deserialization functions
must be registered with the deserializer in advance, using the register_custom_operations func-
tion declared in <caml/custom.h>. Deserialization proceeds by reading the identifier off the input
stream, allocating a custom block of the size specified in the input stream, searching the registered
struct custom_operation blocks for one with the same identifier, and calling its deserialize
function to fill the data part of the custom block.
C expression Returns
Caml_ba_array_val(v)->num_dims number of dimensions
Caml_ba_array_val(v)->dim[i] i-th dimension
Caml_ba_array_val(v)->flags & BIGARRAY_KIND_MASK kind of array elements
Same as caml_ba_alloc, but the sizes of the array in each dimension are listed as extra
arguments in the function call, rather than being passed as an array.
The following example illustrates how statically-allocated C and Fortran arrays can be made avail-
able to OCaml.
let f a b =
let len = Array.length a in
assert (Array.length b = len);
let res = Array.make len 0. in
for i = 0 to len - 1 do
390
Float arrays are unboxed in OCaml, however the C function foo expect its arguments as boxed
floats and returns a boxed float. Hence the OCaml compiler has no choice but to box a.(i) and
b.(i) and unbox the result of foo. This results in the allocation of 3 * len temporary float values.
Now if we annotate the arguments and result with [@unboxed], the native-code compiler will
be able to avoid all these allocations:
external foo
: (float [@unboxed])
-> (float [@unboxed])
-> (float [@unboxed])
= "foo_byte" "foo"
For convenience, when all arguments and the result are annotated with [@unboxed], it is possible
to put the attribute only once on the declaration itself. So we can also write instead:
external foo : float -> float -> float = "foo_byte" "foo" [@@unboxed]
The following table summarize what OCaml types can be unboxed, and what C types should
be used in correspondence:
Similarly, it is possible to pass untagged OCaml integers between OCaml and C. This is done
by annotating the arguments and/or result with [@untagged]:
• caml_release_runtime_system() The calling thread releases the master lock and other
OCaml resources, enabling other threads to run OCaml code in parallel with the execution
of the calling thread.
• caml_acquire_runtime_system() The calling thread re-acquires the master lock and other
OCaml resources. It may block until no other thread uses the OCaml run-time system.
These functions poll for pending signals by calling asynchronous callbacks (section 20.5.3) before
releasing and after acquiring the lock. They can therefore execute arbitrary OCaml code including
raising an asynchronous exception.
After caml_release_runtime_system() was called and until caml_acquire_runtime_system()
is called, the C code must not access any OCaml data, nor call any function of the
run-time system, nor call back into OCaml code. Consequently, arguments provided
by OCaml to the C primitive must be copied into C data structures before calling
caml_release_runtime_system(), and results to be returned to OCaml must be encoded
as OCaml values after caml_acquire_runtime_system() returns.
Example: the following C primitive invokes gethostbyname to find the IP address of a host
name. The gethostbyname function can block for a long time, so we choose to release the OCaml
run-time system while it is running.
CAMLprim stub_gethostbyname(value vname)
{
CAMLparam1 (vname);
CAMLlocal1 (vres);
struct hostent * h;
char * name;
• legacy mode: All path names, environment variables, command line arguments, etc. on the
OCaml side are assumed to be encoded using the current 8-bit code page of the system.
• Unicode mode: All path names, environment variables, command line arguments, etc. on
the OCaml side are assumed to be encoded using UTF-8.
394
In what follows, we say that a string has the OCaml encoding if it is encoded in UTF-8 when
in Unicode mode, in the current code page in legacy mode, or is an arbitrary string under Unix.
A string has the platform encoding if it is encoded in UTF-16 under Windows or is an arbitrary
string under Unix.
From the point of view of the writer of C stubs, the challenges of interacting with Windows
Unicode APIs are twofold:
• The Windows API uses the UTF-16 encoding to support Unicode. The runtime system
performs the necessary conversions so that the OCaml programmer only needs to deal with
the OCaml encoding. C stubs that call Windows Unicode APIs need to use specific runtime
functions to perform the necessary conversions in a compatible way.
• When writing stubs that need to be compiled under both Windows and Unix, the stubs need
to be written in a way that allow the necessary conversions under Windows but that also
work under Unix, where typically nothing particular needs to be done to support Unicode.
The native C character type under Windows is WCHAR, two bytes wide, while under Unix it is
char, one byte wide. A type char_os is defined in <caml/misc.h> that stands for the concrete C
character type of each platform. Strings in the platform encoding are of type char_os *.
The following functions are exposed to help write compatible C stubs. To use them, you need
to include both <caml/misc.h> and <caml/osdeps.h>.
Example We want to bind the function getenv in a way that works both under Unix and
Windows. Under Unix this function has the prototype:
In terms of char_os, both functions take an argument of type char_os * and return a result
of the same type. We begin by choosing the right implementation of the function to bind:
#ifdef _WIN32
#define getenv_os _wgetenv
#else
#define getenv_os getenv
#endif
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/misc.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/osdeps.h>
#include <stdlib.h>
var_name_os = caml_stat_strdup_to_os(String_val(var_name));
var_value_os = getenv_os(var_name_os);
caml_stat_free(var_name_os);
if (var_value_os == NULL)
caml_raise_not_found();
var_value = caml_copy_string_of_os(var_value_os);
CAMLreturn(var_value);
}
396
• OCaml source files and object files (.cmo, .cmx, .ml) comprising the OCaml part of the
library;
• C object files (.o, .a, respectively, .obj, .lib) comprising the C part of the library;
• An OCaml bytecode library .cma incorporating the .cmo and .ml OCaml files given as argu-
ments, and automatically referencing the C library generated with the C object files.
• An OCaml native-code library .cmxa incorporating the .cmx and .ml OCaml files given as
arguments, and automatically referencing the C library generated with the C object files.
• If dynamic linking is supported on the target platform, a .so (respectively, .dll) shared
library built from the C object files given as arguments, and automatically referencing the
support libraries.
-custom
Force the construction of a statically linked library only, even if dynamic linking is supported.
-failsafe
Fall back to building a statically linked library if a problem occurs while building the shared
library (e.g. some of the support libraries are not available as shared libraries).
-Ldir
Add dir to the search path for support libraries (-llib).
-ocamlc cmd
Use cmd instead of ocamlc to call the bytecode compiler.
Chapter 20. Interfacing C with OCaml 397
-ocamlopt cmd
Use cmd instead of ocamlopt to call the native-code compiler.
-o output
Set the name of the generated OCaml library. ocamlmklib will generate output.cma and/or
output.cmxa. If not specified, defaults to a.
-oc outputc
Set the name of the generated C library. ocamlmklib will generate liboutputc.so (if shared
libraries are supported) and liboutputc.a. If not specified, defaults to the output name given
with -o.
OCAML_FLEXLINK
Alternative executable to use instead of the configured value. Primarily used for bootstrap-
ping.
Example Consider an OCaml interface to the standard libz C library for reading and writing
compressed files. Assume this library resides in /usr/local/zlib. This interface is composed of
an OCaml part zip.cmo/zip.cmx and a C part zipstubs.o containing the stub code around the
libz entry points. The following command builds the OCaml libraries zip.cma and zip.cmxa, as
well as the companion C libraries dllzip.so and libzip.a:
Note: This example is on a Unix system. The exact command lines may be different on other
systems.
If shared libraries are not supported, the following commands are performed instead:
Instead of building simultaneously the bytecode library, the native-code library and the C
libraries, ocamlmklib can be called three times to build each separately. Thus,
builds the C libraries dllzip.so and libzip.a. Notice that the support libraries (-lz) and the
corresponding options (-L/usr/local/zlib) must be given on all three invocations of ocamlmklib,
because they are needed at different times depending on whether shared libraries are supported.
Note Programmers which come to rely on the internal API for a use-case which they find realistic
and useful are encouraged to open a request for improvement on the bug tracker.
which breaks in OCaml ≥ 4.10, you should include the minor_gc header:
#include <caml/minor_gc.h>
#include <caml/version.h>
#if OCAML_VERSION >= 41000
...
#else
...
#endif
400
Chapter 21
21.1 Overview
Flambda is the term used to describe a series of optimisation passes provided by the native code
compilers as of OCaml 4.03.
Flambda aims to make it easier to write idiomatic OCaml code without incurring performance
penalties.
To use the Flambda optimisers it is necessary to pass the -flambda option to the OCaml
configure script. (There is no support for a single compiler that can operate in both Flambda
and non-Flambda modes.) Code compiled with Flambda cannot be linked into the same program
as code compiled without Flambda. Attempting to do this will result in a compiler error.
Whether or not a particular ocamlopt uses Flambda may be determined by invoking it with
the -config option and looking for any line starting with “flambda:”. If such a line is present and
says “true”, then Flambda is supported, otherwise it is not.
Flambda provides full optimisation across different compilation units, so long as the .cmx files
for the dependencies of the unit currently being compiled are available. (A compilation unit cor-
responds to a single .ml source file.) However it does not yet act entirely as a whole-program
compiler: for example, elimination of dead code across a complete set of compilation units is not
supported.
Optimisation with Flambda is not currently supported when generating bytecode.
Flambda should not in general affect the semantics of existing programs. Two exceptions to
this rule are: possible elimination of pure code that is being benchmarked (see section 21.14) and
changes in behaviour of code using unsafe operations (see section 21.15).
Flambda does not yet optimise array or string bounds checks. Neither does it take hints for
optimisation from any assertions written by the user in the code.
Consult the Glossary at the end of this chapter for definitions of technical terms used below.
401
402
Commonly-used options:
-O2 Perform more optimisation than usual. Compilation times may be lengthened. (This flag is
an abbreviation for a certain set of parameters described in section 21.5.)
-O3 Perform even more optimisation than usual, possibly including unrolling of recursive func-
tions. Compilation times may be significantly lengthened.
-Oclassic
Make inlining decisions at the point of definition of a function rather than at the call site(s).
This mirrors the behaviour of OCaml compilers not using Flambda. Compared to compilation
using the new Flambda inlining heuristics (for example at -O2) it produces smaller .cmx files,
shorter compilation times and code that probably runs rather slower. When using -Oclassic,
only the following options described in this section are relevant: -inlining-report and
-inline. If any other of the options described in this section are used, the behaviour is
undefined and may cause an error in future versions of the compiler.
-inlining-report
Emit .inlining files (one per round of optimisation) showing all of the inliner’s decisions.
Less commonly-used options:
-remove-unused-arguments
Remove unused function arguments even when the argument is not specialised. This may
have a small performance penalty. See section 21.10.3.
-unbox-closures
Pass free variables via specialised arguments rather than closures (an optimisation for reducing
allocation). See section 21.9.3. This may have a small performance penalty.
Advanced options, only needed for detailed tuning:
-inline
The behaviour depends on whether -Oclassic is used.
• When not in -Oclassic mode, -inline limits the total size of functions considered for
inlining during any speculative inlining search. (See section 21.3.10.) Note that this
parameter does not control the assessment as to whether any particular function may
be inlined. Raising it to excessive amounts will not necessarily cause more functions to
be inlined.
• When in -Oclassic mode, -inline behaves as in previous versions of the compiler: it
is the maximum size of function to be considered for inlining. See section 21.3.2.
-inline-toplevel
The equivalent of -inline but used when speculative inlining starts at toplevel. See section
21.3.10. Not used in -Oclassic mode.
-inline-branch-factor
Controls how the inliner assesses whether a code path is likely to be hot or cold. See section
21.3.9.
Chapter 21. Optimisation with Flambda 403
-inline-indirect-cost, -inline-prim-cost
Likewise.
-inline-lifting-benefit
Controls inlining of functors at toplevel. See section 21.3.9.
-inline-max-depth
The maximum depth of any speculative inlining search. See section 21.3.10.
-inline-max-unroll
The maximum depth of any unrolling of recursive functions during any speculative inlining
search. See section 21.3.10.
-no-unbox-free-vars-of-closures
Do not unbox closure variables. See section 21.9.1.
-no-unbox-specialised-args
Do not unbox arguments to which functions have been specialised. See section 21.9.2.
-rounds
How many rounds of optimisation to perform. See section 21.2.1.
-unbox-closures-factor
Scaling factor for benefit calculation when using -unbox-closures. See section 21.9.3.
Notes
• The set of command line flags relating to optimisation should typically be specified to be the
same across an entire project. Flambda does not currently record the requested flags in the
.cmx files. As such, inlining of functions from previously-compiled units will subject their
code to the optimisation parameters of the unit currently being compiled, rather than those
specified when they were previously compiled. It is hoped to rectify this deficiency in the
future.
• Flambda-specific flags do not affect linking with the exception of affecting the optimisation of
code in the startup file (containing generated functions such as currying helpers). Typically
such optimisation will not be significant, so eliding such flags at link time might be reasonable.
• Flambda-specific flags are silently accepted even when the -flambda option was not provided
to the configure script. (There is no means provided to change this behaviour.) This is
intended to make it more straightforward to run benchmarks with and without the Flambda
optimisers in effect.
• If the first form is used, with a single integer specified, the value will apply to all rounds.
• If the second form is used, zero-based round integers specify values which are to be used only
for those rounds.
The flags -Oclassic, -O2 and -O3 are applied before all other flags, meaning that certain
parameters may be overridden without having to specify every parameter usually invoked by the
given optimisation level.
21.3 Inlining
Inlining refers to the copying of the code of a function to a place where the function is called.
The code of the function will be surrounded by bindings of its parameters to the corresponding
arguments.
The aims of inlining are:
• to reduce the runtime overhead caused by function calls (including setting up for such calls
and returning afterwards);
• to reduce instruction cache misses by expressing frequently-taken paths through the program
using fewer machine instructions; and
let n = fact 4
Chapter 21. Optimisation with Flambda 405
unrolling once at the call site fact 4 produces (with the body of fact unchanged):
let n =
if 4 = 0 then
1
else
4 * fact (4 - 1)
This simplifies to:
let n = 4 * fact 3
Flambda provides significantly enhanced inlining capabilities relative to previous versions of the
compiler.
• It becomes more straightforward to optimise closure allocations since the layout of closures
does not have to be estimated in any way: it is known. Similarly, it becomes more straight-
forward to control which variables end up in which closures, helping to avoid closure bloat.
module M : sig
val i : int
end = struct
let f x =
let g y = x + y in
g
let h = f 3
let i = h 4 (* h is correctly discovered to be g and inlined *)
end
All of this contrasts with the normal Flambda mode, that is to say without -Oclassic, where:
• the inlining decision is made at the call site; and
• recursive functions can be handled, by specialisation (see below).
The Flambda mode is described in the next section.
let g x = f true x
In this case, we would like to inline f into g, because a conditional jump can be eliminated and
the code size should reduce. If the inlining decision has been made after the declaration of f without
seeing the use, its size would have probably made it ineligible for inlining; but at the call site, its
final size can be known. Further, this function should probably not be inlined systematically: if
b is unknown, or indeed false, there is little benefit to trade off against a large increase in code
size. In the existing non-Flambda inliner this isn’t a great problem because chains of inlining were
cut off fairly quickly. However it has led to excessive use of overly-large inlining parameters such
as -inline 10000.
In more detail, at each call site the following procedure is followed:
• Determine whether it is clear that inlining would be beneficial without, for the moment, doing
any inlining within the function itself. (The exact assessment of benefit is described below.)
If so, the function is inlined.
• If inlining the function is not clearly beneficial, then inlining will be performed speculatively
inside the function itself. The search for speculative inlining possibilities is controlled by two
parameters: the inlining threshold and the inlining depth. (These are described in more detail
below.)
Chapter 21. Optimisation with Flambda 407
– If such speculation shows that performing some inlining inside the function would be
beneficial, then such inlining is performed and the resulting function inlined at the
original call site.
– Otherwise, nothing happens.
Inlining within recursive functions of calls to other functions in the same mutually-recursive group
is kept in check by an unrolling depth, described below. This ensures that functions are not
unrolled to excess. (Unrolling is only enabled if -O3 optimisation level is selected and/or the
-inline-max-unroll flag is passed with an argument greater than zero.)
21.3.7 Objects
Method calls to objects are not at present inlined by Flambda.
let f b x =
if b then
x
else
... big expression ...
let g x = f true x
it would be observed that inlining of f would remove:
• one direct call;
• one conditional branch.
Formally, an estimate of runtime performance benefit is computed by first summing the cost of
the operations that are known to be removed as a result of the inlining and subsequent simplification
of the inlined body. The individual costs for the various kinds of operations may be adjusted using
the various -inline-...-cost flags as follows. Costs are specified as integers. All of these flags
accept a single argument describing such integers using the conventions detailed in section 21.2.1.
-inline-alloc-cost
The cost of an allocation.
-inline-branch-cost
The cost of a branch.
-inline-call-cost
The cost of a direct function call.
-inline-indirect-cost
The cost of an indirect function call.
-inline-prim-cost
The cost of a primitive. Primitives encompass operations including arithmetic and memory
access.
(Default values are described in section 21.5 below.)
The initial benefit value is then scaled by a factor that attempts to compensate for the fact that
the current point in the code, if under some number of conditional branches, may be cold. (Flambda
does not currently compute hot and cold paths.) The factor—the estimated probability that the
inliner really is on a hot path—is calculated as (1+f 1
)d
, where f is set by -inline-branch-factor
and d is the nesting depth of branches at the current point. As the inliner descends into more
deeply-nested branches, the benefit of inlining thus lessens.
The resulting benefit value is known as the estimated benefit.
The change in code size is also estimated: morally speaking it should be the change in machine
code size, but since that is not available to the inliner, an approximation is used.
If the estimated benefit exceeds the increase in code size then the inlined version of the function
will be kept. Otherwise the function will not be inlined.
Applications of functors at toplevel will be given an additional benefit (which may be controlled
by the -inline-lifting-benefit flag) to bias inlining in such situations towards keeping the
inlined version.
Chapter 21. Optimisation with Flambda 409
21.4 Specialisation
The inliner may discover a call site to a recursive function where something is known about the
arguments: for example, they may be equal to some other variables currently in scope. In this
situation it may be beneficial to specialise the function to those arguments. This is done by
copying the declaration of the function (and any others involved in any same mutually-recursive
declaration) and noting the extra information about the arguments. The arguments augmented by
this information are known as specialised arguments. In order to try to ensure that specialisation is
not performed uselessly, arguments are only specialised if it can be shown that they are invariant:
in other words, during the execution of the recursive function(s) themselves, the arguments never
change.
410
Unless overridden by an attribute (see below), specialisation of a function will not be attempted
if:
The compiler can prove invariance of function arguments across multiple functions within a
recursive group (although this has some limitations, as shown by the example below).
It should be noted that the unboxing of closures pass (see below) can introduce specialised
arguments on non-recursive functions. (No other place in the compiler currently does this.)
Example: the well-known List.iter function This function might be written like so:
let print_int x =
print_endline (Int.to_string x)
let run xs =
iter print_int (List.rev xs)
let run xs =
let rec iter' f l =
(* The compiler knows: f holds the same value as foo throughout iter'. *)
match l with
| [] -> ()
| h :: t ->
f h;
iter' f t
in
iter' print_int (List.rev xs)
The compiler notes down that for the function iter’, the argument f is specialised to the
constant closure print_int. This means that the body of iter’ may be simplified:
Chapter 21. Optimisation with Flambda 411
let run xs =
let rec iter' f l =
(* The compiler knows: f holds the same value as foo throughout iter'. *)
match l with
| [] -> ()
| h :: t ->
print_int h; (* this is now a direct call *)
iter' f t
in
iter' print_int (List.rev xs)
let run xs =
let rec iter' f l =
(* The compiler knows: f holds the same value as foo throughout iter'. *)
match l with
| [] -> ()
| h :: t ->
print_endline (Int.to_string h);
iter' f t
in
iter' print_int (List.rev xs)
let run xs =
let rec iter' l =
match l with
| [] -> ()
| h :: t ->
print_endline (Int.to_string h);
iter' t
in
iter' (List.rev xs)
Aside on invariant parameters. The compiler cannot currently detect invariance in cases
such as the following.
Parameter Setting
-inline 10
-inline-branch-factor 0.1
-inline-alloc-cost 7
-inline-branch-cost 5
-inline-call-cost 5
-inline-indirect-cost 4
-inline-prim-cost 3
-inline-lifting-benefit 1300
-inline-toplevel 160
-inline-max-depth 1
-inline-max-unroll 0
-unbox-closures-factor 10
Parameter Setting
-inline 25
-inline-branch-factor Same as default
-inline-alloc-cost Double the default
-inline-branch-cost Double the default
-inline-call-cost Double the default
-inline-indirect-cost Double the default
-inline-prim-cost Double the default
-inline-lifting-benefit Same as default
-inline-toplevel 400
-inline-max-depth 2
-inline-max-unroll Same as default
-unbox-closures-factor Same as default
Chapter 21. Optimisation with Flambda 413
Parameter Setting
-inline 50
-inline-branch-factor Same as default
-inline-alloc-cost Triple the default
-inline-branch-cost Triple the default
-inline-call-cost Triple the default
-inline-indirect-cost Triple the default
-inline-prim-cost Triple the default
-inline-lifting-benefit Same as default
-inline-toplevel 800
-inline-max-depth 3
-inline-max-unroll 1
-unbox-closures-factor Same as default
or never specialise the function so long as it has appropriate contextual knowledge, irre-
spective of the size/benefit calculation. @@specialise with no argument is equivalent to
@@specialise always.
@unrolled n
This attribute is attached to a function application and always takes an integer argument.
Each time the inliner sees the attribute it behaves as follows:
A compiler warning will be emitted if it was found impossible to obey an annotation from an
@inlined or @specialised attribute.
let foo x =
(bar [@inlined]) (42 + x)
end [@@inline never]
21.7 Simplification
Simplification, which is run in conjunction with inlining, propagates information (known as ap-
proximations) about which variables hold what values at runtime. Certain relationships between
variables and symbols are also tracked: for example, some variable may be known to always hold
the same value as some other variable; or perhaps some variable may be known to always hold the
value pointed to by some symbol.
The propagation can help to eliminate allocations in cases such as:
Chapter 21. Optimisation with Flambda 415
let f x y =
...
let p = x, y in
...
... (fst p) ... (snd p) ...
The projections from p may be replaced by uses of the variables x and y, potentially meaning
that p becomes unused.
The propagation performed by the simplification pass is also important for discovering which
functions flow to indirect call sites. This can enable the transformation of such call sites into direct
call sites, which makes them eligible for an inlining transformation.
Note that no information is propagated about the contents of strings, even in safe-string
mode, because it cannot yet be guaranteed that they are immutable throughout a given program.
Notes about float arrays The following language semantics apply specifically to constant float
arrays. (By “constant float array” is meant an array consisting entirely of floating point numbers
that are known at compile time. A common case is a literal such as [| 42.0; 43.0; |].
• Constant float arrays at the toplevel are mutable and never shared. (That is to say, for each
such definition there is a distinct symbol in the data section of the object file pointing at the
array.)
• Constant float arrays not at toplevel are mutable and are created each time the expression is
evaluated. This can be thought of as an operation that takes an immutable array (which in
the source code has no associated name; let us call it the initialising array) and duplicates it
into a fresh mutable array.
– If the array is of size four or less, the expression will create a fresh block and write the
values into it one by one. There is no reference to the initialising array as a whole.
– Otherwise, the initialising array is lifted out and subject to the normal constant sharing
procedure; creation of the array consists of bulk copying the initialising array into a fresh
value on the OCaml heap.
416
Example: In the following code, the compiler observes that the closure returned from the
function f contains a variable pair (free in the body of f) that may be split into two separate
variables.
let f x0 x1 =
let pair = x0, x1 in
Printf.printf "foo\n";
fun y ->
fst pair + snd pair + y
let f x0 x1 =
let pair_0 = x0 in
let pair_1 = x1 in
Printf.printf "foo\n";
fun y ->
pair_0 + pair_1 + y
and then:
let f x0 x1 =
Printf.printf "foo\n";
fun y ->
x0 + x1 + y
The allocation of the pair has been eliminated.
This transformation does not operate if it would cause the closure to contain more than twice
as many closure variables as it did beforehand.
Example: Having been given the following code, the compiler will inline loop into f, and then
observe inv being invariant and always the pair formed by adding 42 and 43 to the argument x of
the function f.
let rec loop inv xs =
match xs with
| [] -> fst inv + snd inv
| x::xs -> x + loop2 xs inv
and loop2 ys inv =
match ys with
| [] -> 4
| y::ys -> y - loop inv ys
let f x =
Printf.printf "%d\n" (loop (x + 42, x + 43) [1; 2; 3])
Since the functions have sufficiently few arguments, more specialised arguments will be added.
After some simplification one obtains:
418
let f x =
let rec loop' xs inv_0 inv_1 =
match xs with
| [] -> inv_0 + inv_1
| x::xs -> x + loop2' xs inv_0 inv_1
and loop2' ys inv_0 inv_1 =
match ys with
| [] -> 4
| y::ys -> y - loop' ys inv_0 inv_1
in
Printf.printf "%d\n" (loop' [1; 2; 3] (x + 42) (x + 43))
The allocation of the pair within f has been removed. (Since the two closures for loop’ and
loop2’ are constant they will also be lifted to toplevel with no runtime allocation penalty. This
would also happen without having run the transformation to unbox specialise arguments.)
The transformation to unbox specialised arguments never introduces extra allocation.
The transformation will not unbox arguments if it would result in the original function having
sufficiently many arguments so as to inhibit tail-call optimisation.
The transformation is implemented by creating a wrapper function that accepts the original ar-
guments. Meanwhile, the original function is renamed and extra arguments are added corresponding
to the unboxed specialised arguments; this new function is called from the wrapper. The wrapper
will then be inlined at direct call sites. Indeed, all call sites will be direct unless -unbox-closures
is being used, since they will have been generated by the compiler when originally specialising the
function. (In the case of -unbox-closures other functions may appear with specialised arguments;
in this case there may be indirect calls and these will incur a small penalty owing to having to
bounce through the wrapper. The technique of direct call surrogates used for -unbox-closures is
not used by the transformation to unbox specialised arguments.)
Simple example: In the following code (which might typically occur when g is too large to
inline) the value of x would usually be communicated to the application of the + function via the
closure of g.
Chapter 21. Optimisation with Flambda 419
let f x =
let g y =
x + y
in
(g [@inlined never]) 42
Unboxing of the closure causes the value for x inside g to be passed as an argument to g rather
than through its closure. This means that the closure of g becomes constant and may be lifted to
toplevel, eliminating the runtime allocation.
The transformation is implemented by adding a new wrapper function in the manner of that
used when unboxing specialised arguments. The closure variables are still free in the wrapper, but
the intention is that when the wrapper is inlined at direct call sites, the relevant values are passed
directly to the main function via the new specialised arguments.
Adding such a wrapper will penalise indirect calls to the function (which might exist in arbitrary
places; remember that this transformation is not for example applied only on functions the compiler
has produced as a result of specialisation) since such calls will bounce through the wrapper. To
mitigate this, if a function is small enough when weighed up against the number of free variables
being removed, it will be duplicated by the transformation to obtain two versions: the original (used
for indirect calls, since we can do no better) and the wrapper/rewritten function pair as described
in the previous paragraph. The wrapper/rewritten function pair will only be used at direct call
sites of the function. (The wrapper in this case is known as a direct call surrogate, since it takes
the place of another function—the unchanged version used for indirect calls—at direct call sites.)
The -unbox-closures-factor command line flag, which takes an integer, may be used to
adjust the point at which a function is deemed large enough to be ineligible for duplication. The
benefit of duplication is scaled by the integer before being evaluated against the size.
Harder example: In the following code, there are two closure variables that would typically
cause closure allocations. One is called fv and occurs inside the function baz; the other is called
z and occurs inside the function bar. In this toy (yet sophisticated) example we again use an
attribute to simulate the typical situation where the first argument of baz is too large to inline.
let foo c =
let rec bar zs fv =
match zs with
| [] -> []
| z::zs ->
let rec baz f = function
| [] -> []
| a::l -> let r = fv + ((f [@inlined never]) a) in r :: baz f l
in
(map2 (fun y -> z + y) [z; 2; 3; 4]) @ bar zs fv
in
Printf.printf "%d" (List.length (bar [1; 2; 3; 4] c))
The code resulting from applying -O3 -unbox-closures to this code passes the free variables
via function arguments in order to eliminate all closure allocation in this example (aside from any
that might be performed inside printf).
420
• may be duplicated.
This is done by forming judgements on the effects and the coeffects that might be performed
were the expression to be executed. Effects talk about how the expression might affect the world;
coeffects talk about how the world might affect the expression.
Effects are classified as follows:
No effects:
The expression does not change the observable state of the world. For example, it must not
write to any mutable storage, call arbitrary external functions or change control flow (e.g. by
raising an exception). Note that allocation is not classed as having “no effects” (see below).
• It is assumed in the compiler that expressions with no effects, whose results are not
used, may be eliminated. (This typically happens where the expression in question is
the defining expression of a let; in such cases the let-expression will be eliminated.)
It is further assumed that such expressions with no effects may be duplicated (and thus
possibly executed more than once).
• Exceptions arising from allocation points, for example “out of memory” or exceptions
propagated from finalizers or signal handlers, are treated as “effects out of the ether”
and thus ignored for our determination here of effectfulness. The same goes for floating
point operations that may cause hardware traps on some platforms.
Arbitrary effects:
All other expressions.
No coeffects:
The expression does not observe the effects (in the sense described above) of other expressions.
For example, it must not read from any mutable storage or call arbitrary external functions.
It is assumed in the compiler that, subject to data dependencies, expressions with neither effects
nor coeffects may be reordered with respect to other expressions.
422
let f x =
let a = 42, x in
(Obj.magic a : int ref) := 1;
fst a
The reason this is unsafe is because the simplification pass believes that fst a holds the value
42; and indeed it must, unless type soundness has been broken via unsafe operations.
If it must be the case that code has to be written that triggers warning 59, but the code is
known to actually be correct (for some definition of correct), then Sys.opaque_identity may be
used to wrap the value before unsafe operations are performed upon it. Great care must be taken
when doing this to ensure that the opacity is added at the correct place. It must be emphasised
that this use of Sys.opaque_identity is only for exceptional cases. It should not be used in
normal code or to try to guide the optimiser.
As an example, this code will return the integer 1:
let f x =
let a = Sys.opaque_identity (42, x) in
(Obj.magic a : int ref) := 1;
fst a
Chapter 21. Optimisation with Flambda 423
let f x =
let a = 42, x in
Sys.opaque_identity (Obj.magic a : int ref) := 1;
fst a
High levels of inlining performed by Flambda may expose bugs in code thought previously to
be correct. Take care, for example, not to add type annotations that claim some mutable value is
always immediate if it might be possible for an unsafe operation to update it to a boxed value.
21.16 Glossary
The following terminology is used in this chapter of the manual.
Call site
See direct call site and indirect call site below.
Closed function
A function whose body has no free variables except its parameters and any to which are
bound other functions within the same (possibly mutually-recursive) declaration.
Closure
The runtime representation of a function. This includes pointers to the code of the function
together with the values of any variables that are used in the body of the function but
actually defined outside of the function, in the enclosing scope. The values of such variables,
collectively known as the environment, are required because the function may be invoked
from a place where the original bindings of such variables are no longer in scope. A group of
possibly mutually-recursive functions defined using let rec all share a single closure. (Note to
developers: in the Flambda source code a closure always corresponds to a single function; a
set of closures refers to a group of such.)
Closure variable
A member of the environment held within the closure of a given function.
Constant
Some entity (typically an expression) the value of which is known by the compiler at com-
pile time. Constantness may be explicit from the source code or inferred by the Flambda
optimisers.
Constant closure
A closure that is statically allocated in an object file. It is almost always the case that the
environment portion of such a closure is empty.
Defining expression
The expression e in let x = e in e’.
424
Program
A collection of symbol bindings forming the definition of a single compilation unit (i.e. .cmx
file).
Specialised argument
An argument to a function that is known to always hold a particular value at runtime. These
are introduced by the inliner when specialising recursive functions; and the unbox-closures
pass. (See section 21.4.)
Symbol
A name referencing a particular place in an object file or executable image. At that particular
place will be some constant value. Symbols may be examined using operating system-specific
tools (for example objdump on Linux).
Symbol binding
Analogous to a let-expression but working at the level of symbols defined in the object file.
The address of a symbol is fixed, but it may be bound to both constant and non-constant
expressions.
Toplevel
An expression in the current program which is not enclosed within any function declaration.
Variable
A named entity to which some OCaml value is bound by a let expression, pattern-matching
construction, or similar.
Chapter 22
22.1 Overview
American fuzzy lop (“afl-fuzz”) is a fuzzer, a tool for testing software by providing randomly-
generated inputs, searching for those inputs which cause the program to crash.
Unlike most fuzzers, afl-fuzz observes the internal behaviour of the program being tested, and
adjusts the test cases it generates to trigger unexplored execution paths. As a result, test cases
generated by afl-fuzz cover more of the possible behaviours of the tested program than other fuzzers.
This requires that programs to be tested are instrumented to communicate with afl-fuzz. The
native-code compiler “ocamlopt” can generate such instrumentation, allowing afl-fuzz to be used
against programs written in OCaml.
For more information on afl-fuzz, see the website at http://lcamtuf.coredump.cx/afl/
22.3 Example
As an example, we fuzz-test the following program, readline.ml:
425
426
let _ =
let s = read_line () in
match Array.to_list (Array.init (String.length s) (String.get s)) with
['s'; 'e'; 'c'; 'r'; 'e'; 't'; ' '; 'c'; 'o'; 'd'; 'e'] -> failwith "uh oh"
| _ -> ()
There is a single input (the string “secret code”) which causes this program to crash, but finding
it by blind random search is infeasible.
Instead, we compile with afl-fuzz instrumentation enabled:
mkdir input
echo asdf > input/testcase
mkdir output
afl-fuzz -i input -o output ./readline
By inspecting instrumentation output, the fuzzer finds the crashing input quickly.
Chapter 23
This chapter describes the OCaml instrumented runtime, a runtime variant allowing the collection
of events and metrics.
Collected metrics include time spent executing the garbage collector. The overall execution time
of individual pauses are measured down to the time spent in specific parts of the garbage collection.
Insight is also given on memory allocation and motion by recording the size of allocated memory
blocks, as well as value promotions from the minor heap to the major heap.
23.1 Overview
Once compiled and linked with the instrumented runtime, any OCaml program can generate trace
files that can then be read and analyzed by users in order to understand specific runtime behaviors.
The generated trace files are stored using the Common Trace Format, which is a general purpose
binary tracing format. A complete trace consists of:
• and a trace file, generated by the runtime in the program being traced.
427
428
let () =
seq 1_000_000
|> Seq.fold_left (fun m i -> SMap.add (s i) i m) SMap.empty
|> clear
|> ignore
The next step is to compile and link the program with the instrumented runtime. This can be
done by using the -runtime-variant flag:
Note that the instrumented runtime is an alternative runtime for OCaml programs. It is only
referenced during the linking stage of the final executable. This means that the compilation stage
does not need to be altered to enable instrumentation.
The resulting program can then be traced by running it with the environment variable
OCAML_EVENTLOG_ENABLED:
OCAML_EVENTLOG_ENABLED=1 ./program
During execution, a trace file will be generated in the program’s current working directory.
(executable
(name program)
(flags "-runtime-variant=i"))
The instrumented runtime can also be used with the OCaml bytecode interpreter. This can be
done by either using the -runtime-variant=i flag when linking the program with ocamlc, or by
running the generated bytecode through ocamlruni:
See chapter 11 and chapter 13 for more information about ocamlc and ocamlrun.
23.3.1 eventlog-tools
eventlog-tools is a library implementing a parser, as well as a a set of tools that allows to perform
basic format conversions and analysis.
For more information about eventlog-tools, refer to the project’s main page: https://github.com/ocaml-
multicore/eventlog-tools
23.3.2 babeltrace
babeltrace is a C library, as well as a Python binding and set of tools that serve as the reference
implementation for the Common Trace Format. The babeltrace command line utility allows for a
basic rendering of a trace’s content, while the high level Python API can be used to decode the
trace and process them programmatically with libraries such as numpy or Jupyter.
Unlike eventlog-tools, which possesses a specific knowledge of OCaml’s Common Trace Format
schema, it is required to provide the OCaml metadata file to babeltrace.
The metadata file is available in the OCaml installation. Its location can be obtained using the
following command:
ocamlc -where
The eventlog_metadata file can be found at this path and copied in the same directory as the
generated trace file. However, babeltrace expects the file to be named metadata in order to process
the trace. Thus, it will need to be renamed when copied to the trace’s directory.
Here is a naive decoder example, using babeltrace’s Python library, and Python 3.8:
import subprocess
import shutil
import sys
import babeltrace as bt
def print_event(ev):
print(ev['timestamp'])
print(ev['pid'])
if ev.name == "entry":
print('entry_event')
print(ev['phase'])
if ev.name == "exit":
print('exit_event')
print(ev['phase'])
if ev.name == "alloc":
print(ev['count'])
print(ev['bucket'])
if ev.name == "counter":
print(ev['count'])
print(ev['kind'])
if ev.name == "flush":
430
print("flush")
def get_ocaml_dir():
# Fetching OCaml's installation directory to extract the CTF metadata
ocamlc_where = subprocess.run(['ocamlc', '-where'], stdout=subprocess.PIPE)
ocaml_dir = ocamlc_where.stdout.decode('utf-8').rstrip('\n')
return(ocaml_dir)
def main():
trace_dir = sys.argv[1]
ocaml_dir = get_ocaml_dir()
metadata_path = ocaml_dir + "/eventlog_metadata"
# copying the metadata to the trace's directory,
# and renaming it to 'metadata'.
shutil.copyfile(metadata_path, trace_dir + "/metadata")
tr = bt.TraceCollection()
tr.add_trace(trace_dir, 'ctf')
for event in tr.events:
print_event(event)
if __name__ == '__main__':
main()
This script expect to receive as an argument the directory containing the trace file. It will then
copy the CTF metadata file to the trace’s directory, and then decode the trace, printing each event
in the process.
For more information on babeltrace, see the website at: https://babeltrace.org/
Note as well that parent directories in the given path will not be created when opening the
trace. The runtime assumes the path is accessible for creating and writing the trace. The program
will fail to start if this requirement isn’t met.
==== eventlog/flush
median flush time: 207.8us
total flush time: 938.1us
flush count: 5
432
23.4.3 Limitations
The instrumented runtime does not support the fork system call. A child process forked from an
instrumented program will not be traced.
The instrumented runtime aims to provide insight into the runtime’s execution while main-
taining a low overhead. However, this overhead may become more noticeable depending on how a
program executes. The instrumented runtime currently puts a strong emphasis on tracing garbage
collection events. This means that programs with heavy garbage collection activity may be more
susceptible to tracing induced performance penalties.
While providing an accurate estimate of potential performance loss is difficult, test on various
OCaml programs showed a total running time increase ranging from 1% to 8%.
For a program with an extended running time where the collection of only a small sample of
events is required, using the eventlog_resume and eventlog_pause primitives may help relieve some
of the tracing induced performance impact.
Part IV
433
Chapter 24
This chapter describes the OCaml core library, which is composed of declarations for built-in types
and exceptions, plus the module Stdlib that provides basic operations on these built-in types. The
Stdlib module is special in two ways:
• It is automatically linked with the user’s object code files by the ocamlc command (chap-
ter 11).
Conventions
The declarations of the built-in types and the components of module Stdlib are printed one by
one in typewriter font, followed by a short comment. All library modules and the components they
provide are indexed at the end of this report.
Built-in types
type int
The type of integer numbers.
type char
The type of characters.
type bytes
435
436
Predefined exceptions
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 match keyword in the source code (file name, line number, column number).
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. (Not reliable for allocations on the minor heap.)
exception Stack_overflow
Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal
size. This often indicates infinite or excessively deep recursion in the user’s program. Before
4.10, it was not fully implemented by the native-code compiler.
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 integer division and remainder operations when their second argument
is zero.
438
exception Sys_blocked_io
A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel.
Exceptions
val raise : exn -> 'a
Raise the given exception value
exception Exit
The Exit exception is not raised by any library function. It is provided for use in your
programs.
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. (Not reliable for allocations on the minor heap.)
exception Stack_overflow
Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal
size. This often indicates infinite or excessively deep recursion in the user’s program.
Before 4.10, it was not fully implemented by the native-code compiler.
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 integer division and remainder operations when their second argument
is zero.
exception Sys_blocked_io
A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel.
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.
Left-associative operator, see Ocaml_operators[25.54] for more information.
Return the smaller of the two arguments. The result is unspecified if one of the arguments
contains the float value nan.
Boolean operations
val not : bool -> bool
The boolean negation.
Debugging
val __LOC__ : string
__LOC__ returns the location at which this expression appears in the file currently being
parsed by the compiler, with the standard error format of OCaml: "File %S, line %d,
characters %d-%d".
Since: 4.02.0
Composition operators
val (|>) : 'a -> ('a -> 'b) -> 'b
Reverse-application operator: x |> f |> g is exactly equivalent to g (f (x)).
Left-associative operator, see Ocaml_operators[25.54] for more information.
Since: 4.01
Integer arithmetic
Integers are Sys.int_size bits wide. All operations are taken modulo 2Sys.int_size . They do not
fail on overflow.
val (~-) : int -> int
Unary negation. You can also write - e instead of ~- e. Unary operator, see
Ocaml_operators[25.54] for more information.
Bitwise operations
val (land) : int -> int -> int
Bitwise logical and. Left-associative operator, see Ocaml_operators[25.54] for more
information.
Bitwise logical exclusive or. Left-associative operator, see Ocaml_operators[25.54] for more
information.
Floating-point arithmetic
OCaml’s floating-point numbers follow the IEEE 754 standard, using double precision (64 bits)
numbers. Floating-point operations never raise an exception on overflow, underflow, division by
zero, etc. Instead, special IEEE numbers are returned as appropriate, such as infinity for 1.0 /.
0.0, neg_infinity for -1.0 /. 0.0, and nan (’not a number’) for 0.0 /. 0.0. These special
numbers then propagate through floating-point computations as expected: for instance, 1.0 /.
infinity is 0.0, basic arithmetic operations (+., -., *., /.) with nan as an argument return nan,
...
val (~-.) : float -> float
Unary negation. You can also write -. e instead of ~-. e. Unary operator, see
Ocaml_operators[25.54] for more information.
Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]. Result is in
radians and ranges over the entire real line.
Since: 4.13.0
type fpclass =
| FP_normal
Normal number, none of the below
| FP_subnormal
Number very close to 0.0, has reduced precision
| FP_zero
Number is 0.0 or -0.0
| FP_infinite
Number is positive or negative infinity
| FP_nan
Not a number: result of an undefined operation
The five classes of floating-point numbers, as determined by the classify_float[24.2]
function.
String operations
More string operations are provided in module String[24.2].
val (^) : string -> string -> string
String concatenation. Right-associative operator, see Ocaml_operators[25.54] for more
information.
Raises Invalid_argument if the result is longer then than Sys.max_string_length[25.50]
bytes.
Character operations
More character operations are provided in module Char[24.2].
val int_of_char : char -> int
Return the ASCII code of the argument.
Unit operations
val ignore : 'a -> unit
Discard the value of its argument and return (). For instance, ignore(f x) discards the
result of the side-effecting function f. It is equivalent to f x; (), except that the latter
may generate a compiler warning; writing ignore(f x) instead avoids the warning.
Pair operations
val fst : 'a * 'b -> 'a
Return the first component of a pair.
List operations
More list operations are provided in module List[24.2].
val (@) : 'a list -> 'a list -> 'a list
List concatenation. Not tail-recursive (length of the first argument). Right-associative
operator, see Ocaml_operators[25.54] for more information.
Input/output
Note: all input/output functions can raise Sys_error when the system calls they invoke fail.
type in_channel
The type of input channel.
type out_channel
The type of output channel.
val open_out_gen : open_flag list -> int -> string -> out_channel
open_out_gen mode perm filename opens the named file for writing, as described above.
The extra argument mode specifies the opening mode. The extra argument perm specifies
the file permissions, in case the file must be created. open_out[24.2] and
open_out_bin[24.2] are special cases of this function.
val output : out_channel -> bytes -> int -> int -> unit
output oc buf pos len writes len characters from byte sequence buf, starting at offset
pos, to the given output channel oc.
Raises Invalid_argument if pos and len do not designate a valid range of buf.
val output_substring : out_channel -> string -> int -> int -> unit
Same as output but take a string as argument instead of a byte sequence.
Since: 4.02.0
Close the given channel, flushing all buffered write operations. Output functions raise a
Sys_error exception when they are applied to a closed output channel, except close_out
and flush, which do nothing when applied to an already closed channel. Note that
close_out may raise Sys_error if the operating system signals an error when flushing or
closing.
val open_in_gen : open_flag list -> int -> string -> in_channel
open_in_gen mode perm filename opens the named file for reading, as described above.
The extra arguments mode and perm specify the opening mode and file permissions.
open_in[24.2] and open_in_bin[24.2] are special cases of this function.
val input : in_channel -> bytes -> int -> int -> int
458
input ic buf pos len reads up to len characters from the given channel ic, storing them
in byte sequence buf, starting at character number pos. 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 not all requested
len characters were read, either because no more characters were available at that time, or
because the implementation found it convenient to do a partial read; input must be called
again to read the remaining characters, if desired. (See also really_input[24.2] for reading
exactly len characters.) Exception Invalid_argument "input" is raised if pos and len do
not designate a valid range of buf.
val really_input : in_channel -> bytes -> int -> int -> unit
really_input ic buf pos len reads len characters from channel ic, storing them in byte
sequence buf, starting at character number pos.
Raises
• End_of_file if the end of file is reached before len characters have been read.
• Invalid_argument if pos and len do not designate a valid range of buf.
Operations on large files. This sub-module provides 64-bit variants of the channel functions
that manipulate file positions and file sizes. By representing positions and sizes by 64-bit
integers (type int64) instead of regular integers (type int), these alternate functions allow
operating on files whose sizes are greater than max_int.
References
type 'a ref =
{ mutable contents : 'a ;
}
The type of references (mutable indirection cells) containing a value of type 'a.
Result type
type ('a, 'b) result =
| Ok of 'a
| Error of 'b
Since: 4.03.0
Chapter 24. The core library 461
• conversions specifications, introduced by the special character '%' followed by one or more
characters specifying what kind of argument to read or print,
• formatting indications, introduced by the special character '@' followed by one or more
characters specifying how to read or print the argument,
• plain characters that are regular characters with usual lexical conventions. Plain characters
specify string literals to be read in the input or printed in the output.
There is an additional lexical rule to escape the special characters '%' and '@' in format strings:
if a special character follows a '%' character, it is treated as a plain character. In other words,
"%%" is considered as a plain '%' and "%@" as a plain '@'.
For more information about conversion specifications and formatting indications available, read
the documentation of modules Scanf[24.2], Printf[24.2] and Format[24.2].
Format strings have a general and highly polymorphic type ('a, 'b, 'c, 'd, 'e, 'f)
format6. The two simplified types, format and format4 below are included for backward
compatibility with earlier releases of OCaml.
The meaning of format string type parameters is as follows:
• 'a is the type of the parameters of the format for formatted output functions (printf-style
functions); 'a is the type of the values read by the format for formatted input functions
(scanf-style functions).
• 'b is the type of input source for formatted input functions and the type of output target
for formatted output functions. For printf-style functions from module Printf[24.2], 'b is
typically out_channel; for printf-style functions from module Format[24.2], 'b is typically
Format.formatter[25.18]; for scanf-style functions from module Scanf[24.2], 'b is typically
Scanf.Scanning.in_channel[25.42].
Type argument 'b is also the type of the first argument given to user’s defined printing functions
for %a and %t conversions, and user’s defined reading functions for %r conversion.
• 'c is the type of the result of the %a and %t printing functions, and also the type of the
argument transmitted to the first argument of kprintf-style functions or to the kscanf-style
functions.
• 'e is the type of the receiver function for the scanf-style functions.
462
• 'f is the final result type of a formatted input/output function invocation: for the printf-
style functions, it is typically unit; for the scanf-style functions, it is typically the result
type of the receiver function.
type ('a, 'b, 'c, 'd, 'e, 'f) format6 = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.forma
type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
Converts a format string into a string.
val format_of_string :
('a, 'b, 'c, 'd, 'e, 'f) format6 ->
('a, 'b, 'c, 'd, 'e, 'f) format6
format_of_string s returns a format string read from the string literal s. Note:
format_of_string can not convert a string argument that is not a literal. If you need this
functionality, use the more general Scanf.format_from_string[25.42] function.
val (^^) :
('a, 'b, 'c, 'd, 'e, 'f) format6 ->
('f, 'b, 'c, 'e, 'g, 'h) format6 ->
('a, 'b, 'c, 'd, 'g, 'h) format6
f1 ^^ f2 catenates format strings f1 and f2. The result is a format string that behaves as
the concatenation of format strings f1 and f2: in case of formatted output, it accepts
arguments from f1, then arguments from f2; in case of formatted input, it returns results
from f1, then results from f2. Right-associative operator, see Ocaml_operators[25.54] for
more information.
Program termination
val exit : int -> 'a
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. All open output channels
are flushed with flush_all. An implicit exit 0 is performed each time a program
terminates normally. An implicit exit 2 is performed if the program terminates early
because of an uncaught exception.
Gc
module Genlex :
Genlex
module Hashtbl :
Hashtbl
module Int :
Int
module Int32 :
Int32
module Int64 :
Int64
module Lazy :
Lazy
module Lexing :
Lexing
module List :
List
module ListLabels :
ListLabels
module Map :
Map
module Marshal :
Marshal
module MoreLabels :
MoreLabels
module Nativeint :
Nativeint
module Obj :
Obj
module Oo :
Oo
module Option :
Option
module Parsing :
Parsing
module Pervasives :
Pervasives
module Printexc :
Printexc
module Printf :
Printf
Chapter 24. The core library 465
module Queue :
Queue
module Random :
Random
module Result :
Result
module Scanf :
Scanf
module Seq :
Seq
module Set :
Set
module Stack :
Stack
module StdLabels :
StdLabels
module Stream :
Stream
module String :
String
module StringLabels :
StringLabels
module Sys :
Sys
module Uchar :
Uchar
module Unit :
Unit
module Weak :
Weak
466
Chapter 25
This chapter describes the functions provided by the OCaml 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 core Stdlib module, submodules are not automatically “opened” when 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.
467
468
Data structures:
String p. 728 string operations
Bytes p. 513 operations on byte sequences
Array p. 474 array operations
List p. 634 list operations
StdLabels p. 726 labelized versions of the above 4 modules
Unit p. 756 unit values
Bool p. 507 boolean values
Char p. 538 character operations
Uchar p. 755 Unicode characters
Int p. 618 integer values
Option p. 687 option values
Result p. 705 result values
Either p. 542 either values
Hashtbl p. 608 hash tables and hash functions
Random p. 703 pseudo-random number generator
Set p. 719 sets over ordered types
Map p. 650 association tables over ordered types
MoreLabels p. 659 labelized versions of Hashtbl, Set, and Map
Oo p. 687 useful functions on objects
Stack p. 725 last-in first-out stacks
Queue p. 701 first-in first-out queues
Buffer p. 508 buffers that grow on demand
Seq p. 717 functional iterators
Lazy p. 628 delayed evaluation
Weak p. 757 references that don’t prevent objects from being garbage-collected
Atomic p. 485 atomic references (for compatibility with concurrent runtimes)
Ephemeron p. 543 ephemerons and weak hash tables
Bigarray p. 486 large, multi-dimensional, numerical arrays
Arithmetic:
Complex p. 539 complex numbers
Float p. 555 floating-point numbers
Int32 p. 620 operations on 32-bit integers
Int64 p. 624 operations on 64-bit integers
Nativeint p. 683 operations on platform-native integers
input/output:
Format p. 572 pretty printing with automatic indentation and line breaking
Marshal p. 656 marshaling of data structures
Printf p. 697 formatting printing functions
Scanf p. 707 formatted input functions
Digest p. 540 MD5 message digest
Chapter 25. The standard library 469
Parsing:
Genlex p. 607 a generic lexer over streams
Lexing p. 631 the run-time library for lexers generated by ocamllex
Parsing p. 689 the run-time library for parsers generated by ocamlyacc
Stream p. 727 basic functions over streams
System interface:
Arg p. 469 parsing of command line arguments
Callback p. 537 registering OCaml functions to be called from C
Filename p. 551 operations on file names
Gc p. 598 memory management control and statistics
Printexc p. 690 a catch-all exception handler
Sys p. 747 system interface
Misc:
Fun p. 597 function values
let speclist =
[("-verbose", Arg.Set verbose, "Output debug information");
("-o", Arg.Set_string output_file, "Set output file name")]
let () =
Arg.parse speclist anon_fun usage_msg;
(* Main functionality here *)
Syntax of command lines: A keyword is a character string starting with a -. An option is a key-
word alone or followed by an argument. The types of keywords are: Unit, Bool, Set, Clear, String,
Set_string, Int, Set_int, Float, Set_float, Tuple, Symbol, Rest, Rest_all and Expand.
Unit, Set and Clear keywords take no argument.
470
A Rest or Rest_all keyword takes the remainder of the command line as arguments. (More
explanations below.)
Every other keyword takes the following word on the command line as argument. For compati-
bility with GNU getopt_long, keyword=arg is also allowed. Arguments not preceded by a keyword
are called anonymous arguments.
Examples (cmd is assumed to be the command name):
• cmd a b – c d (two anonymous arguments and a rest option with two arguments)
Rest takes a function that is called repeatedly for each remaining command line argument.
Rest_all takes a function that is called once, with the list of all remaining arguments.
Note that if no arguments follow a Rest keyword then the function is not called at all whereas
the function for a Rest_all keyword is called with an empty list.
type spec =
| Unit of (unit -> unit)
Call the function with unit argument
| Bool of (bool -> unit)
Call the function with a bool 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
| Set_string of string ref
Set the reference to the string argument
| Int of (int -> unit)
Call the function with an int argument
| Set_int of int ref
Set the reference to the int argument
| Float of (float -> unit)
Chapter 25. The standard library 471
val parse_dynamic :
(key * spec * doc) list ref ->
anon_fun -> usage_msg -> unit
Same as Arg.parse[25.1], except that the speclist argument is a reference and may be
updated during the parsing. A typical use for this feature is to parse command lines of the
form:
• command subcommand options where the list of options depends on the value of the
subcommand argument.
Since: 4.01.0
val parse_argv :
?current:int ref ->
string array ->
(key * spec * doc) list -> anon_fun -> usage_msg -> unit
Arg.parse_argv ~current args speclist anon_fun usage_msg parses the array args as
if it were the command line. It uses and updates the value of ~current (if given), or
Arg.current[25.1]. You must set it before calling parse_argv. The initial value of current
is the index of the program name (argument 0) in the array. If an error occurs,
Arg.parse_argv raises Arg.Bad[25.1] with the error message as argument. If option -help
or –help is given, Arg.parse_argv raises Arg.Help[25.1] with the help message as
argument.
val parse_argv_dynamic :
?current:int ref ->
string array ->
(key * spec * doc) list ref ->
anon_fun -> string -> unit
Same as Arg.parse_argv[25.1], except that the speclist argument is a reference and may
be updated during the parsing. See Arg.parse_dynamic[25.1].
Since: 4.01.0
val parse_and_expand_argv_dynamic :
int ref ->
string array ref ->
(key * spec * doc) list ref ->
anon_fun -> string -> unit
Same as Arg.parse_argv_dynamic[25.1], except that the argv argument is a reference and
may be updated during the parsing of Expand arguments. See
Arg.parse_argv_dynamic[25.1].
Since: 4.05.0
val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit
Chapter 25. The standard library 473
Same as Arg.parse[25.1], except that the Expand arguments are allowed and the
Arg.current[25.1] reference is not updated.
Since: 4.05.0
val usage : (key * spec * doc) list -> usage_msg -> unit
Arg.usage speclist usage_msg prints to standard error an error message that includes
the list of valid options. This is the same message that Arg.parse[25.1] prints in case of
error. speclist and usage_msg are the same as for Arg.parse[25.1].
val usage_string : (key * spec * doc) list -> usage_msg -> string
Returns the message that would have been printed by Arg.usage[25.1], if provided with the
same parameters.
val align :
?limit:int ->
(key * spec * doc) list -> (key * spec * doc) list
Align the documentation strings by inserting spaces at the first alignment separator (tab or,
if tab is not found, space), according to the length of the keyword. Use a alignment
separator as the first character in a doc string if you want to align the whole string. The
doc strings corresponding to Symbol arguments are aligned on the next line.
Arg.write_arg file args writes the arguments args newline-terminated into the file
file. If the any of the arguments in args contains a newline, use Arg.write_arg0[25.1]
instead.
Since: 4.05.0
val set : 'a array -> int -> 'a -> unit
set a n x modifies array a in place, replacing element number n with x. You can also write
a.(n) <- x instead of set a n x.
Raises Invalid_argument if n is outside the range 0 to length a - 1.
val init : int -> (int -> 'a) -> 'a array
init n f returns a fresh array of length n, with element number i initialized to the result
of f i. In other terms, init n f tabulates the results of f applied to the integers 0 to n-1.
Raises Invalid_argument if n < 0 or n > Sys.max_array_length. If the return type of f
is float, then the maximum size is only Sys.max_array_length / 2.
val make_matrix : int -> int -> 'a -> 'a array array
make_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).
Raises Invalid_argument if dimx or dimy is negative or greater than
Sys.max_array_length[25.50]. If the value of e is a floating-point number, then the
maximum size is only Sys.max_array_length / 2.
val create_matrix : int -> int -> 'a -> 'a array array
Deprecated. create_matrix is an alias for Array.make_matrix[25.2].
val append : 'a array -> 'a array -> 'a array
append v1 v2 returns a fresh array containing the concatenation of the arrays v1 and v2.
Raises Invalid_argument if length v1 + length v2 > Sys.max_array_length.
val sub : 'a array -> int -> int -> 'a array
sub a pos len returns a fresh array of length len, containing the elements number pos to
pos + len - 1 of array a.
Raises Invalid_argument if pos and len do not designate a valid subarray of a; that is, if
pos < 0, or len < 0, or pos + len > length a.
val fill : 'a array -> int -> int -> 'a -> unit
fill a pos len x modifies the array a in place, storing x in elements number pos to pos
+ len - 1.
Raises Invalid_argument if pos and len do not designate a valid subarray of a.
476
val blit : 'a array -> int -> 'a array -> int -> int -> unit
blit src src_pos dst dst_pos len copies len elements from array src, starting at
element number src_pos, to array dst, starting at element number dst_pos. It works
correctly even if src and dst are the same array, and the source and destination chunks
overlap.
Raises Invalid_argument if src_pos and len do not designate a valid subarray of src, or
if dst_pos and len do not designate a valid subarray of dst.
Iterators
val iter : ('a -> unit) -> 'a array -> unit
iter f a applies function f in turn to all the elements of a. It is equivalent to f a.(0); f
a.(1); ...; f a.(length a - 1); ().
val iteri : (int -> 'a -> unit) -> 'a array -> unit
Same as Array.iter[25.2], but the function is applied to the index of the element as first
argument, and the element itself as second argument.
val map : ('a -> 'b) -> 'a array -> 'b 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.(length a - 1) |].
val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array
Same as Array.map[25.2], but the function is applied to the index of the element as first
argument, and the element itself as second argument.
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
fold_left f init a computes f (... (f (f init a.(0)) a.(1)) ...) a.(n-1),
where n is the length of the array a.
val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array
fold_left_map is a combination of Array.fold_left[25.2] and Array.map[25.2] that
threads an accumulator through calls to f.
Since: 4.13.0
val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a
fold_right f a init computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...)),
where n is the length of the array a.
Chapter 25. The standard library 477
val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
map2 f a b applies function f to all the elements of a and b, and builds an array with the
results returned by f: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b -
1)|].
Since: 4.03.0 (4.05.0 in ArrayLabels)
Raises Invalid_argument if the arrays are not the same size.
Array scanning
val for_all : ('a -> bool) -> 'a array -> bool
for_all f [|a1; ...; an|] checks if all elements of the array satisfy the predicate f.
That is, it returns (f a1) && (f a2) && ... && (f an).
Since: 4.03.0
val exists : ('a -> bool) -> 'a array -> bool
exists f [|a1; ...; an|] checks if at least one element of the array satisfies the
predicate f. That is, it returns (f a1) || (f a2) || ... || (f an).
Since: 4.03.0
val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as Array.for_all[25.2], but for a two-argument predicate.
Since: 4.11.0
Raises Invalid_argument if the two arrays have different lengths.
val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as Array.exists[25.2], but for a two-argument predicate.
Since: 4.11.0
Raises Invalid_argument if the two arrays have different lengths.
val find_opt : ('a -> bool) -> 'a array -> 'a option
find_opt f a returns the first element of the array a that satisfies the predicate f, or None
if there is no value that satisfies f in the array a.
Since: 4.13.0
val find_map : ('a -> 'b option) -> 'a array -> 'b option
find_map f a applies f to the elements of a in order, and returns the first result of the
form Some v, or None if none exist.
Since: 4.13.0
Arrays of pairs
val split : ('a * 'b) array -> 'a array * 'b array
split [|(a1,b1); ...; (an,bn)|] is ([|a1; ...; an|], [|b1; ...; bn|]).
Since: 4.13.0
val combine : 'a array -> 'b array -> ('a * 'b) array
combine [|a1; ...; an|] [|b1; ...; bn|] is [|(a1,b1); ...; (an,bn)|]. Raise
Invalid_argument if the two arrays have different lengths.
Since: 4.13.0
Sorting
val sort : ('a -> 'a -> int) -> 'a array -> unit
Sort an array in increasing order according to a comparison function. The comparison
function must return 0 if its arguments compare as equal, a positive integer if the first is
greater, and a negative integer if the first is smaller (see below for a complete specification).
For example, compare[24.2] is a suitable comparison function. After calling sort, the array
is sorted in place in increasing order. sort is guaranteed to run in constant heap space and
(at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a be the array and cmp the comparison
function. The following must be true for all x, y, z in a :
When sort returns, a contains the same elements as before, reordered in such a way that
for all i and j valid indices of a :
val stable_sort : ('a -> 'a -> int) -> 'a array -> unit
Same as Array.sort[25.2], but the sorting algorithm is stable (i.e. elements that compare
equal are kept in their original order) and not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary array of length n/2,
where n is the length of the array. It is usually faster than the current implementation of
Array.sort[25.2].
val fast_sort : ('a -> 'a -> int) -> 'a array -> unit
Same as Array.sort[25.2] or Array.stable_sort[25.2], whichever is faster on typical input.
get a n returns the element number n of array a. The first element has number 0. The last
element has number length a - 1. You can also write a.(n) instead of get a n.
Raises Invalid_argument if n is outside the range 0 to (length a - 1).
val set : 'a array -> int -> 'a -> unit
set a n x modifies array a in place, replacing element number n with x. You can also write
a.(n) <- x instead of set a n x.
Raises Invalid_argument if n is outside the range 0 to length a - 1.
val init : int -> f:(int -> 'a) -> 'a array
init n ~f returns a fresh array of length n, with element number i initialized to the result
of f i. In other terms, init n ~f tabulates the results of f applied to the integers 0 to n-1.
Raises Invalid_argument if n < 0 or n > Sys.max_array_length. If the return type of f
is float, then the maximum size is only Sys.max_array_length / 2.
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
make_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).
Raises Invalid_argument if dimx or dimy is negative or greater than
Sys.max_array_length[25.50]. If the value of e is a floating-point number, then the
maximum size is only Sys.max_array_length / 2.
val create_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
Chapter 25. The standard library 481
val append : 'a array -> 'a array -> 'a array
append v1 v2 returns a fresh array containing the concatenation of the arrays v1 and v2.
Raises Invalid_argument if length v1 + length v2 > Sys.max_array_length.
val sub : 'a array -> pos:int -> len:int -> 'a array
sub a ~pos ~len returns a fresh array of length len, containing the elements number pos
to pos + len - 1 of array a.
Raises Invalid_argument if pos and len do not designate a valid subarray of a; that is, if
pos < 0, or len < 0, or pos + len > length a.
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
fill a ~pos ~len x modifies the array a in place, storing x in elements number pos to
pos + len - 1.
Raises Invalid_argument if pos and len do not designate a valid subarray of a.
val blit :
src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit
blit ~src ~src_pos ~dst ~dst_pos ~len copies len elements from array src, starting at
element number src_pos, to array dst, starting at element number dst_pos. It works
correctly even if src and dst are the same array, and the source and destination chunks
overlap.
Raises Invalid_argument if src_pos and len do not designate a valid subarray of src, or
if dst_pos and len do not designate a valid subarray of dst.
Iterators
val iter : f:('a -> unit) -> 'a array -> unit
iter ~f a applies function f in turn to all the elements of a. It is equivalent to f a.(0); f
a.(1); ...; f a.(length a - 1); ().
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
Same as ArrayLabels.iter[25.3], but the function is applied to the index of the element as
first argument, and the element itself as second argument.
val map : f:('a -> 'b) -> 'a array -> 'b 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.(length a - 1) |].
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
Same as ArrayLabels.map[25.3], but the function is applied to the index of the element as
first argument, and the element itself as second argument.
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
fold_left ~f ~init a computes f (... (f (f init a.(0)) a.(1)) ...) a.(n-1),
where n is the length of the array a.
val fold_left_map :
f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b array -> 'a * 'c array
fold_left_map is a combination of ArrayLabels.fold_left[25.3] and
ArrayLabels.map[25.3] that threads an accumulator through calls to f.
Since: 4.13.0
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
fold_right ~f a ~init computes f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...)),
where n is the length of the array a.
Array scanning
val for_all : f:('a -> bool) -> 'a array -> bool
for_all ~f [|a1; ...; an|] checks if all elements of the array satisfy the predicate f.
That is, it returns (f a1) && (f a2) && ... && (f an).
Since: 4.03.0
val exists : f:('a -> bool) -> 'a array -> bool
exists ~f [|a1; ...; an|] checks if at least one element of the array satisfies the
predicate f. That is, it returns (f a1) || (f a2) || ... || (f an).
Since: 4.03.0
val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as ArrayLabels.for_all[25.3], but for a two-argument predicate.
Since: 4.11.0
Raises Invalid_argument if the two arrays have different lengths.
val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as ArrayLabels.exists[25.3], but for a two-argument predicate.
Since: 4.11.0
Raises Invalid_argument if the two arrays have different lengths.
val find_opt : f:('a -> bool) -> 'a array -> 'a option
find_opt ~f a returns the first element of the array a that satisfies the predicate f, or
None if there is no value that satisfies f in the array a.
Since: 4.13.0
val find_map : f:('a -> 'b option) -> 'a array -> 'b option
find_map ~f a applies f to the elements of a in order, and returns the first result of the
form Some v, or None if none exist.
Since: 4.13.0
484
Arrays of pairs
val split : ('a * 'b) array -> 'a array * 'b array
split [|(a1,b1); ...; (an,bn)|] is ([|a1; ...; an|], [|b1; ...; bn|]).
Since: 4.13.0
val combine : 'a array -> 'b array -> ('a * 'b) array
combine [|a1; ...; an|] [|b1; ...; bn|] is [|(a1,b1); ...; (an,bn)|]. Raise
Invalid_argument if the two arrays have different lengths.
Since: 4.13.0
Sorting
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
Sort an array in increasing order according to a comparison function. The comparison
function must return 0 if its arguments compare as equal, a positive integer if the first is
greater, and a negative integer if the first is smaller (see below for a complete specification).
For example, compare[24.2] is a suitable comparison function. After calling sort, the array
is sorted in place in increasing order. sort is guaranteed to run in constant heap space and
(at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a be the array and cmp the comparison
function. The following must be true for all x, y, z in a :
When sort returns, a contains the same elements as before, reordered in such a way that
for all i and j valid indices of a :
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
Same as ArrayLabels.sort[25.3], but the sorting algorithm is stable (i.e. elements that
compare equal are kept in their original order) and not guaranteed to run in constant heap
space.
The current implementation uses Merge Sort. It uses a temporary array of length n/2,
where n is the length of the array. It is usually faster than the current implementation of
ArrayLabels.sort[25.3].
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
Same as ArrayLabels.sort[25.3] or ArrayLabels.stable_sort[25.3], whichever is faster
on typical input.
Chapter 25. The standard library 485
type 'a t
An atomic (mutable) reference to a value of type 'a.
compare_and_set r seen v sets the new value of r to v only if its current value is
physically equal to seen – the comparison and the set occur atomically. Returns true if the
comparison succeeded (so the set happened) and false otherwise.
Users of this module are encouraged to do open Bigarray in their source, then refer to array
types and operations via short dot notation, e.g. Array1.t or Array2.sub.
Bigarrays support all the OCaml ad-hoc polymorphic operations:
• and structured input-output (the functions from the Marshal[25.31] module, as well as
output_value[24.2] and input_value[24.2]).
Element kinds
Bigarrays can contain elements of the following kinds:
• platform-native signed integers (32 bits on 32-bit architectures, 64 bits on 64-bit architectures)
(Bigarray.nativeint_elt[25.5]).
Each element kind is represented at the type level by one of the *_elt types defined below
(defined with a single constructor instead of abstract types for technical injectivity reasons).
type float32_elt =
| Float32_elt
type float64_elt =
| Float64_elt
type int8_signed_elt =
488
| Int8_signed_elt
type int8_unsigned_elt =
| Int8_unsigned_elt
type int16_signed_elt =
| Int16_signed_elt
type int16_unsigned_elt =
| Int16_unsigned_elt
type int32_elt =
| Int32_elt
type int64_elt =
| Int64_elt
type int_elt =
| Int_elt
type nativeint_elt =
| Nativeint_elt
type complex32_elt =
| Complex32_elt
type complex64_elt =
| Complex64_elt
type ('a, 'b) kind =
| Float32 : (float, float32_elt) kind
| Float64 : (float, float64_elt) kind
| Int8_signed : (int, int8_signed_elt) kind
| Int8_unsigned : (int, int8_unsigned_elt) kind
| Int16_signed : (int, int16_signed_elt) kind
| Int16_unsigned : (int, int16_unsigned_elt) kind
| Int32 : (int32, int32_elt) kind
| Int64 : (int64, int64_elt) kind
| Int : (int, int_elt) kind
| Nativeint : (nativeint, nativeint_elt) kind
| Complex32 : (Complex.t, complex32_elt) kind
| Complex64 : (Complex.t, complex64_elt) kind
| Char : (char, int8_unsigned_elt) kind
To each element kind is associated an OCaml type, which is the type of OCaml values that
can be stored in the Bigarray or read back from it. This type is not necessarily the same as
the type of the array elements proper: for instance, a Bigarray whose elements are of kind
float32_elt contains 32-bit single precision floats, but reading or writing one of its
elements from OCaml uses the OCaml type float, which is 64-bit double precision floats.
The GADT type ('a, 'b) kind captures this association of an OCaml type 'a for values
read or written in the Bigarray, and of an element kind 'b which represents the actual
contents of the Bigarray. Its constructors list all possible associations of OCaml types with
element kinds, and are re-exported below for backward-compatibility reasons.
Chapter 25. The standard library 489
Using a generalized algebraic datatype (GADT) here allows writing well-typed polymorphic
functions whose return type depend on the argument type, such as:
See Bigarray.char[25.5].
Array layouts
type c_layout =
| C_layout_typ
See Bigarray.fortran_layout[25.5].
type fortran_layout =
| Fortran_layout_typ
To facilitate interoperability with existing C and Fortran code, this library supports two
different memory layouts for Bigarrays, one compatible with the C conventions, the other
compatible with the Fortran conventions.
In the C-style layout, array indices start at 0, and multi-dimensional arrays are laid out in
row-major format. That is, for a two-dimensional array, all elements of row 0 are contiguous
in memory, followed by all elements of row 1, etc. In other terms, the array elements at
(x,y) and (x, y+1) are adjacent in memory.
In the Fortran-style layout, array indices start at 1, and multi-dimensional arrays are laid
out in column-major format. That is, for a two-dimensional array, all elements of column 0
are contiguous in memory, followed by all elements of column 1, etc. In other terms, the
array elements at (x,y) and (x+1, y) are adjacent in memory.
Each layout style is identified at the type level by the phantom types
Bigarray.c_layout[25.5] and Bigarray.fortran_layout[25.5] respectively.
Chapter 25. The standard library 491
Supported layouts
The GADT type 'a layout represents one of the two supported memory layouts: C-style or
Fortran-style. Its constructors are re-exported as values below for backward-compatibility reasons.
type 'a layout =
| C_layout : c_layout layout
| Fortran_layout : fortran_layout layout
val c_layout : c_layout layout
val fortran_layout : fortran_layout layout
val create :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> int array -> ('a, 'b, 'c) t
Genarray.create kind layout dimensions returns a new Bigarray whose element
kind is determined by the parameter kind (one of float32, float64, int8_signed,
etc) and whose layout is determined by the parameter layout (one of c_layout or
fortran_layout). The dimensions parameter is an array of integers that indicate the
size of the Bigarray in each dimension. The length of dimensions determines the
number of dimensions of the Bigarray.
For instance, Genarray.create int32 c_layout [|4;6;8|] returns a fresh Bigarray
of 32-bit integers, in C layout, having three dimensions, the three dimensions being 4, 6
and 8 respectively.
Bigarrays returned by Genarray.create are not initialized: the initial values of array
elements is unspecified.
Genarray.create raises Invalid_argument if the number of dimensions is not in the
range 0 to 16 inclusive, or if one of the dimensions is negative.
492
val init :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout ->
int array -> (int array -> 'a) -> ('a, 'b, 'c) t
Genarray.init kind layout dimensions f returns a new Bigarray b whose element
kind is determined by the parameter kind (one of float32, float64, int8_signed,
etc) and whose layout is determined by the parameter layout (one of c_layout or
fortran_layout). The dimensions parameter is an array of integers that indicate the
size of the Bigarray in each dimension. The length of dimensions determines the
number of dimensions of the Bigarray.
Each element Genarray.get b i is initialized to the result of f i. In other words,
Genarray.init kind layout dimensions f tabulates the results of f applied to the
indices of a new Bigarray whose layout is described by kind, layout and dimensions.
The index array i may be shared and mutated between calls to f.
For instance, Genarray.init int c_layout [|2; 1; 3|] (Array.fold_left (+)
0) returns a fresh Bigarray of integers, in C layout, having three dimensions (2, 1, 3,
respectively), with the element values 0, 1, 2, 1, 2, 3.
Genarray.init raises Invalid_argument if the number of dimensions is not in the
range 0 to 16 inclusive, or if one of the dimensions is negative.
Since: 4.12.0
val get : ('a, 'b, 'c) t -> int array -> 'a
Read an element of a generic Bigarray. Genarray.get a [|i1; ...; iN|] returns the
element of a whose coordinates are i1 in the first dimension, i2 in the second
dimension, . . ., iN in the N-th dimension.
If a has C layout, the coordinates must be greater or equal than 0 and strictly less than
the corresponding dimensions of a. If a has Fortran layout, the coordinates must be
greater or equal than 1 and less or equal than the corresponding dimensions of a.
If N > 3, alternate syntax is provided: you can write a.{i1, i2, ..., iN} instead of
Genarray.get a [|i1; ...; iN|]. (The syntax a.{...} with one, two or three
coordinates is reserved for accessing one-, two- and three-dimensional arrays as
described below.)
Raises Invalid_argument if the array a does not have exactly N dimensions, or if the
coordinates are outside the array bounds.
val set : ('a, 'b, 'c) t -> int array -> 'a -> unit
Assign an element of a generic Bigarray. Genarray.set a [|i1; ...; iN|] v stores
the value v in the element of a whose coordinates are i1 in the first dimension, i2 in
the second dimension, . . ., iN in the N-th dimension.
The array a must have exactly N dimensions, and all coordinates must lie inside the
array bounds, as described for Genarray.get; otherwise, Invalid_argument is raised.
If N > 3, alternate syntax is provided: you can write a.{i1, i2, ..., iN} <- v
instead of Genarray.set a [|i1; ...; iN|] v. (The syntax a.{...} <- v with
one, two or three coordinates is reserved for updating one-, two- and three-dimensional
arrays as described below.)
val sub_left :
('a, 'b, Bigarray.c_layout) t ->
int -> int -> ('a, 'b, Bigarray.c_layout) t
Extract a sub-array of the given Bigarray by restricting the first (left-most) dimension.
Genarray.sub_left a ofs len returns a Bigarray with the same number of
dimensions as a, and the same dimensions as a, except the first dimension, which
494
corresponds to the interval [ofs ... ofs + len - 1] of the first dimension of a. No
copying of elements is involved: the sub-array and the original array share the same
storage space. In other terms, the element at coordinates [|i1; ...; iN|] of the
sub-array is identical to the element at coordinates [|i1+ofs; ...; iN|] of the
original array a.
Genarray.sub_left applies only to Bigarrays in C layout.
Raises Invalid_argument if ofs and len do not designate a valid sub-array of a, that
is, if ofs < 0, or len < 0, or ofs + len > Genarray.nth_dim a 0.
val sub_right :
('a, 'b, Bigarray.fortran_layout) t ->
int -> int -> ('a, 'b, Bigarray.fortran_layout) t
Extract a sub-array of the given Bigarray by restricting the last (right-most)
dimension. Genarray.sub_right a ofs len returns a Bigarray with the same
number of dimensions as a, and the same dimensions as a, except the last dimension,
which corresponds to the interval [ofs ... ofs + len - 1] of the last dimension of
a. No copying of elements is involved: the sub-array and the original array share the
same storage space. In other terms, the element at coordinates [|i1; ...; iN|] of
the sub-array is identical to the element at coordinates [|i1; ...; iN+ofs|] of the
original array a.
Genarray.sub_right applies only to Bigarrays in Fortran layout.
Raises Invalid_argument if ofs and len do not designate a valid sub-array of a, that
is, if ofs < 1, or len < 0, or ofs + len > Genarray.nth_dim a
(Genarray.num_dims a - 1).
val slice_left :
('a, 'b, Bigarray.c_layout) t ->
int array -> ('a, 'b, Bigarray.c_layout) t
Extract a sub-array of lower dimension from the given Bigarray by fixing one or several
of the first (left-most) coordinates. Genarray.slice_left a [|i1; ... ; iM|]
returns the ’slice’ of a obtained by setting the first M coordinates to i1, . . ., iM. If a has
N dimensions, the slice has dimension N - M, and the element at coordinates [|j1;
...; j(N-M)|] in the slice is identical to the element at coordinates [|i1; ...; iM;
j1; ...; j(N-M)|] in the original array a. No copying of elements is involved: the
slice and the original array share the same storage space.
Genarray.slice_left applies only to Bigarrays in C layout.
Raises Invalid_argument if M >= N, or if [|i1; ... ; iM|] is outside the bounds
of a.
val slice_right :
('a, 'b, Bigarray.fortran_layout) t ->
int array -> ('a, 'b, Bigarray.fortran_layout) t
Extract a sub-array of lower dimension from the given Bigarray by fixing one or several
of the last (right-most) coordinates. Genarray.slice_right a [|i1; ... ; iM|]
Chapter 25. The standard library 495
returns the ’slice’ of a obtained by setting the last M coordinates to i1, . . ., iM. If a has
N dimensions, the slice has dimension N - M, and the element at coordinates [|j1;
...; j(N-M)|] in the slice is identical to the element at coordinates [|j1; ...;
j(N-M); i1; ...; iM|] in the original array a. No copying of elements is involved:
the slice and the original array share the same storage space.
Genarray.slice_right applies only to Bigarrays in Fortran layout.
Raises Invalid_argument if M >= N, or if [|i1; ... ; iM|] is outside the bounds
of a.
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
Copy all elements of a Bigarray in another Bigarray. Genarray.blit src dst copies
all elements of src into dst. Both arrays src and dst must have the same number of
dimensions and equal dimensions. Copying a sub-array of src to a sub-array of dst
can be achieved by applying Genarray.blit to sub-array or slices of src and dst.
end
Zero-dimensional arrays
module Array0 :
sig
type ('a, 'b, 'c) t
The type of zero-dimensional Bigarrays whose elements have OCaml type 'a,
representation kind 'b, and memory layout 'c.
val init :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> 'a -> ('a, 'b, 'c) t
Array0.init kind layout v behaves like Array0.create kind layout except that
the element is additionally initialized to the value v.
Since: 4.12.0
496
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
Copy the first Bigarray to the second Bigarray. See Bigarray.Genarray.blit[25.5] for
more details.
val of_value :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> 'a -> ('a, 'b, 'c) t
Build a zero-dimensional Bigarray initialized from the given value.
end
Zero-dimensional arrays. The Array0 structure provides operations similar to those of
Bigarray.Genarray[25.5], but specialized to the case of zero-dimensional arrays that only
contain a single scalar value. Statically knowing the number of dimensions of the array
allows faster operations, and more precise static type-checking.
Since: 4.05.0
Chapter 25. The standard library 497
One-dimensional arrays
module Array1 :
sig
type ('a, 'b, 'c) t
The type of one-dimensional Bigarrays whose elements have OCaml type 'a,
representation kind 'b, and memory layout 'c.
val create :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> int -> ('a, 'b, 'c) t
Array1.create kind layout dim returns a new Bigarray of one dimension, whose
size is dim. kind and layout determine the array element kind and the array layout as
described for Bigarray.Genarray.create[25.5].
val init :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> int -> (int -> 'a) -> ('a, 'b, 'c) t
Array1.init kind layout dim f returns a new Bigarray b of one dimension, whose
size is dim. kind and layout determine the array element kind and the array layout as
described for Bigarray.Genarray.create[25.5].
Each element Array1.get b i of the array is initialized to the result of f i.
In other words, Array1.init kind layout dimensions f tabulates the results of f
applied to the indices of a new Bigarray whose layout is described by kind, layout and
dim.
Since: 4.12.0
val set : ('a, 'b, 'c) t -> int -> 'a -> unit
Array1.set a x v, also written a.{x} <- v, stores the value v at index x in a. x
must be inside the bounds of a as described in Bigarray.Array1.get[25.5]; otherwise,
Invalid_argument is raised.
val slice : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) Bigarray.Array0.t
Extract a scalar (zero-dimensional slice) of the given one-dimensional Bigarray. The
integer parameter is the index of the scalar to extract. See
Bigarray.Genarray.slice_left[25.5] and Bigarray.Genarray.slice_right[25.5]
for more details.
Since: 4.05.0
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
Copy the first Bigarray to the second Bigarray. See Bigarray.Genarray.blit[25.5] for
more details.
val of_array :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> 'a array -> ('a, 'b, 'c) t
Build a one-dimensional Bigarray initialized from the given array.
val unsafe_set : ('a, 'b, 'c) t -> int -> 'a -> unit
Like Bigarray.Array1.set[25.5], but bounds checking is not always performed. Use
with caution and only when the program logic guarantees that the access is within
bounds.
end
Two-dimensional arrays
module Array2 :
sig
type ('a, 'b, 'c) t
The type of two-dimensional Bigarrays whose elements have OCaml type 'a,
representation kind 'b, and memory layout 'c.
val create :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> int -> int -> ('a, 'b, 'c) t
Array2.create kind layout dim1 dim2 returns a new Bigarray of two dimensions,
whose size is dim1 in the first dimension and dim2 in the second dimension. kind and
layout determine the array element kind and the array layout as described for
Bigarray.Genarray.create[25.5].
val init :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout ->
int -> int -> (int -> int -> 'a) -> ('a, 'b, 'c) t
Array2.init kind layout dim1 dim2 f returns a new Bigarray b of two dimensions,
whose size is dim2 in the first dimension and dim2 in the second dimension. kind and
layout determine the array element kind and the array layout as described for
Bigarray.Genarray.create[25.5].
Each element Array2.get b i j of the array is initialized to the result of f i j.
500
In other words, Array2.init kind layout dim1 dim2 f tabulates the results of f
applied to the indices of a new Bigarray whose layout is described by kind, layout,
dim1 and dim2.
Since: 4.12.0
val get : ('a, 'b, 'c) t -> int -> int -> 'a
Array2.get a x y, also written a.{x,y}, returns the element of a at coordinates (x,
y). x and y must be within the bounds of a, as described for
Bigarray.Genarray.get[25.5]; otherwise, Invalid_argument is raised.
val set : ('a, 'b, 'c) t -> int -> int -> 'a -> unit
Array2.set a x y v, or alternatively a.{x,y} <- v, stores the value v at coordinates
(x, y) in a. x and y must be within the bounds of a, as described for
Bigarray.Genarray.set[25.5]; otherwise, Invalid_argument is raised.
Chapter 25. The standard library 501
val sub_left :
('a, 'b, Bigarray.c_layout) t ->
int -> int -> ('a, 'b, Bigarray.c_layout) t
Extract a two-dimensional sub-array of the given two-dimensional Bigarray by
restricting the first dimension. See Bigarray.Genarray.sub_left[25.5] for more
details. Array2.sub_left applies only to arrays with C layout.
val sub_right :
('a, 'b, Bigarray.fortran_layout) t ->
int -> int -> ('a, 'b, Bigarray.fortran_layout) t
Extract a two-dimensional sub-array of the given two-dimensional Bigarray by
restricting the second dimension. See Bigarray.Genarray.sub_right[25.5] for more
details. Array2.sub_right applies only to arrays with Fortran layout.
val slice_left :
('a, 'b, Bigarray.c_layout) t ->
int -> ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t
Extract a row (one-dimensional slice) of the given two-dimensional Bigarray. The
integer parameter is the index of the row to extract. See
Bigarray.Genarray.slice_left[25.5] for more details. Array2.slice_left applies
only to arrays with C layout.
val slice_right :
('a, 'b, Bigarray.fortran_layout) t ->
int -> ('a, 'b, Bigarray.fortran_layout) Bigarray.Array1.t
Extract a column (one-dimensional slice) of the given two-dimensional Bigarray. The
integer parameter is the index of the column to extract. See
Bigarray.Genarray.slice_right[25.5] for more details. Array2.slice_right applies
only to arrays with Fortran layout.
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
Copy the first Bigarray to the second Bigarray. See Bigarray.Genarray.blit[25.5] for
more details.
val of_array :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> 'a array array -> ('a, 'b, 'c) t
Build a two-dimensional Bigarray initialized from the given array of arrays.
502
val unsafe_get : ('a, 'b, 'c) t -> int -> int -> 'a
Like Bigarray.Array2.get[25.5], but bounds checking is not always performed.
val unsafe_set : ('a, 'b, 'c) t -> int -> int -> 'a -> unit
Like Bigarray.Array2.set[25.5], but bounds checking is not always performed.
end
Three-dimensional arrays
module Array3 :
sig
type ('a, 'b, 'c) t
The type of three-dimensional Bigarrays whose elements have OCaml type 'a,
representation kind 'b, and memory layout 'c.
val create :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> int -> int -> int -> ('a, 'b, 'c) t
Array3.create kind layout dim1 dim2 dim3 returns a new Bigarray of three
dimensions, whose size is dim1 in the first dimension, dim2 in the second dimension,
and dim3 in the third. kind and layout determine the array element kind and the
array layout as described for Bigarray.Genarray.create[25.5].
val init :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout ->
int ->
int -> int -> (int -> int -> int -> 'a) -> ('a, 'b, 'c) t
Array3.init kind layout dim1 dim2 dim3 f returns a new Bigarray b of three
dimensions, whose size is dim1 in the first dimension, dim2 in the second dimension,
and dim3 in the third. kind and layout determine the array element kind and the
array layout as described for Bigarray.Genarray.create[25.5].
Each element Array3.get b i j k of the array is initialized to the result of f i j k.
In other words, Array3.init kind layout dim1 dim2 dim3 f tabulates the results
of f applied to the indices of a new Bigarray whose layout is described by kind,
layout, dim1, dim2 and dim3.
Since: 4.12.0
Chapter 25. The standard library 503
val get : ('a, 'b, 'c) t -> int -> int -> int -> 'a
Array3.get a x y z, also written a.{x,y,z}, returns the element of a at coordinates
(x, y, z). x, y and z must be within the bounds of a, as described for
Bigarray.Genarray.get[25.5]; otherwise, Invalid_argument is raised.
val set : ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
Array3.set a x y v, or alternatively a.{x,y,z} <- v, stores the value v at
coordinates (x, y, z) in a. x, y and z must be within the bounds of a, as described for
Bigarray.Genarray.set[25.5]; otherwise, Invalid_argument is raised.
val sub_left :
('a, 'b, Bigarray.c_layout) t ->
int -> int -> ('a, 'b, Bigarray.c_layout) t
504
val sub_right :
('a, 'b, Bigarray.fortran_layout) t ->
int -> int -> ('a, 'b, Bigarray.fortran_layout) t
Extract a three-dimensional sub-array of the given three-dimensional Bigarray by
restricting the second dimension. See Bigarray.Genarray.sub_right[25.5] for more
details. Array3.sub_right applies only to arrays with Fortran layout.
val slice_left_1 :
('a, 'b, Bigarray.c_layout) t ->
int -> int -> ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t
Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the
first two coordinates. The integer parameters are the coordinates of the slice to
extract. See Bigarray.Genarray.slice_left[25.5] for more details.
Array3.slice_left_1 applies only to arrays with C layout.
val slice_right_1 :
('a, 'b, Bigarray.fortran_layout) t ->
int -> int -> ('a, 'b, Bigarray.fortran_layout) Bigarray.Array1.t
Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the
last two coordinates. The integer parameters are the coordinates of the slice to extract.
See Bigarray.Genarray.slice_right[25.5] for more details. Array3.slice_right_1
applies only to arrays with Fortran layout.
val slice_left_2 :
('a, 'b, Bigarray.c_layout) t ->
int -> ('a, 'b, Bigarray.c_layout) Bigarray.Array2.t
Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the
first coordinate. The integer parameter is the first coordinate of the slice to extract.
See Bigarray.Genarray.slice_left[25.5] for more details. Array3.slice_left_2
applies only to arrays with C layout.
val slice_right_2 :
('a, 'b, Bigarray.fortran_layout) t ->
int -> ('a, 'b, Bigarray.fortran_layout) Bigarray.Array2.t
Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the
last coordinate. The integer parameter is the coordinate of the slice to extract. See
Bigarray.Genarray.slice_right[25.5] for more details. Array3.slice_right_2
applies only to arrays with Fortran layout.
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
Chapter 25. The standard library 505
Copy the first Bigarray to the second Bigarray. See Bigarray.Genarray.blit[25.5] for
more details.
val of_array :
('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> 'a array array array -> ('a, 'b, 'c) t
Build a three-dimensional Bigarray initialized from the given array of arrays of arrays.
val unsafe_get : ('a, 'b, 'c) t -> int -> int -> int -> 'a
Like Bigarray.Array3.get[25.5], but bounds checking is not always performed.
val unsafe_set : ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
Like Bigarray.Array3.set[25.5], but bounds checking is not always performed.
end
val genarray_of_array1 : ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given one-dimensional Bigarray.
val genarray_of_array2 : ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given two-dimensional Bigarray.
val genarray_of_array3 : ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given three-dimensional Bigarray.
val array0_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array0.t
Return the zero-dimensional Bigarray corresponding to the given generic Bigarray.
Since: 4.05.0
Raises Invalid_argument if the generic Bigarray does not have exactly zero dimension.
506
val array1_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array1.t
Return the one-dimensional Bigarray corresponding to the given generic Bigarray.
Raises Invalid_argument if the generic Bigarray does not have exactly one dimension.
val array2_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array2.t
Return the two-dimensional Bigarray corresponding to the given generic Bigarray.
Raises Invalid_argument if the generic Bigarray does not have exactly two dimensions.
val array3_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array3.t
Return the three-dimensional Bigarray corresponding to the given generic Bigarray.
Raises Invalid_argument if the generic Bigarray does not have exactly three dimensions.
Re-shaping Bigarrays
val reshape :
('a, 'b, 'c) Genarray.t ->
int array -> ('a, 'b, 'c) Genarray.t
reshape b [|d1;...;dN|] converts the Bigarray b to a N-dimensional array of dimensions
d1. . .dN. The returned array and the original array b share their data and have the same
layout. For instance, assuming that b is a one-dimensional array of dimension 12, reshape
b [|3;4|] returns a two-dimensional array b' of dimensions 3 and 4. If b has C layout, the
element (x,y) of b' corresponds to the element x * 3 + y of b. If b has Fortran layout,
the element (x,y) of b' corresponds to the element x + (y - 1) * 4 of b. The returned
Bigarray must have exactly the same number of elements as the original Bigarray b. That
is, the product of the dimensions of b must be equal to i1 * ... * iN. Otherwise,
Invalid_argument is raised.
val reshape_0 : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array0.t
Specialized version of Bigarray.reshape[25.5] for reshaping to zero-dimensional arrays.
Since: 4.05.0
val reshape_1 : ('a, 'b, 'c) Genarray.t -> int -> ('a, 'b, 'c) Array1.t
Specialized version of Bigarray.reshape[25.5] for reshaping to one-dimensional arrays.
val reshape_2 :
('a, 'b, 'c) Genarray.t ->
int -> int -> ('a, 'b, 'c) Array2.t
Specialized version of Bigarray.reshape[25.5] for reshaping to two-dimensional arrays.
val reshape_3 :
('a, 'b, 'c) Genarray.t ->
int -> int -> int -> ('a, 'b, 'c) Array3.t
Specialized version of Bigarray.reshape[25.5] for reshaping to three-dimensional arrays.
Chapter 25. The standard library 507
Booleans
type t = bool =
| false
| true
The type of booleans (truth values).
The constructors false and true are included here so that they have paths, but they are
not intended to be used in user-defined data types.
Converting
val to_int : bool -> int
to_int b is 0 if b is false and 1 if b is true.
let concat_strings ss =
let b = Buffer.create 16 in
List.iter (Buffer.add_string b) ss;
Buffer.contents b
type t
The abstract type of buffers.
val blit : t -> int -> bytes -> int -> int -> unit
Buffer.blit src srcoff dst dstoff len copies len characters from the current
contents of the buffer src, starting at offset srcoff to dst, starting at character dstoff.
Since: 3.11.2
Raises Invalid_argument if srcoff and len do not designate a valid range of src, or if
dstoff and len do not designate a valid range of dst.
Chapter 25. The standard library 509
Appending
Note: all add_* operations can raise Failure if the internal byte sequence of the buffer would need
to grow beyond Sys.max_string_length[25.50].
val add_char : t -> char -> unit
add_char b c appends the character c at the end of buffer b.
val add_substring : t -> string -> int -> int -> unit
add_substring b s ofs len takes len characters from offset ofs in string s and appends
them at the end of buffer b.
Raises Invalid_argument if ofs and len do not designate a valid range of s.
val add_subbytes : t -> bytes -> int -> int -> unit
add_subbytes b s ofs len takes len characters from offset ofs in byte sequence s and
appends them at the end of buffer b.
Since: 4.02
Raises Invalid_argument if ofs and len do not designate a valid range of s.
val add_substitute : t -> (string -> string) -> string -> unit
add_substitute b f s appends the string pattern s at the end of buffer b with
substitution. The substitution process looks for variables into the pattern and substitutes
each variable name by its value, as obtained by applying the mapping f to the variable
name. Inside the string pattern, a variable name immediately follows a non-escaped $
character and is one of the following:
• End_of_file if the channel contains fewer than n characters. In this case, the
characters are still added to the buffer, so as to avoid loss of data.
• Invalid_argument if len < 0 or len > Sys.max_string_length.
make n c returns a new byte sequence of length n, filled with the byte c.
Raises Invalid_argument if n < 0 or n > Sys.max_string_length[25.50].
val fill : bytes -> int -> int -> char -> unit
fill s pos len c modifies s in place, replacing len characters with c, starting at pos.
Raises Invalid_argument if pos and len do not designate a valid range of s.
val blit : bytes -> int -> bytes -> int -> int -> unit
Chapter 25. The standard library 515
blit src src_pos dst dst_pos len copies len bytes from sequence src, starting at
index src_pos, to sequence dst, starting at index dst_pos. It works correctly even if src
and dst are the same byte sequence, and the source and destination intervals overlap.
Raises Invalid_argument if src_pos and len do not designate a valid range of src, or if
dst_pos and len do not designate a valid range of dst.
val blit_string : string -> int -> bytes -> int -> int -> unit
blit src src_pos dst dst_pos len copies len bytes from string src, starting at index
src_pos, to byte sequence dst, starting at index dst_pos.
Since: 4.05.0 in BytesLabels
Raises Invalid_argument if src_pos and len do not designate a valid range of src, or if
dst_pos and len do not designate a valid range of dst.
val iteri : (int -> char -> unit) -> bytes -> unit
Same as Bytes.iter[25.8], but the function is applied to the index of the byte as first
argument and the byte itself as second argument.
val mapi : (int -> char -> char) -> bytes -> bytes
mapi f s calls f with each character of s and its index (in increasing index order) and
stores the resulting bytes in a new sequence that is returned as the result.
val fold_left : ('a -> char -> 'a) -> 'a -> bytes -> 'a
516
val fold_right : (char -> 'a -> 'a) -> bytes -> 'a -> 'a
fold_right f s x computes f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x)
...)), where n is the length of s.
Since: 4.13.0
rindex_opt s c returns the index of the last occurrence of byte c in s or None if c does not
occur in s.
Since: 4.05
val index_from_opt : bytes -> int -> char -> int option
index_from_opt s i c returns the index of the first occurrence of byte c in s after
position i or None if c does not occur in s after position i. index_opt s c is equivalent to
index_from_opt s 0 c.
Since: 4.05
Raises Invalid_argument if i is not a valid position in s.
val rindex_from_opt : bytes -> int -> char -> int option
rindex_from_opt s i c returns the index of the last occurrence of byte c in s before
position i+1 or None if c does not occur in s before position i+1. rindex_opt s c is
equivalent to rindex_from s (length s - 1) c.
Since: 4.05
Raises Invalid_argument if i+1 is not a valid position in s.
type t = bytes
An alias for the type of byte sequences.
Unique ownership is linear: passing the data to another piece of code means giving up
ownership (we cannot write the data again). A unique owner may decide to make the data
shared (giving up mutation rights on it), but shared data may not become uniquely-owned
again.
unsafe_to_string s can only be used when the caller owns the byte sequence s – either
uniquely or as shared immutable data. The caller gives up ownership of s, and gains
ownership of the returned string.
520
There are two valid use-cases that respect this ownership discipline:
1. Creating a string by initializing and mutating a byte sequence that is never changed after
initialization is performed.
This function is safe because the byte sequence s will never be accessed or mutated after
unsafe_to_string is called. The string_init code gives up ownership of s, and returns
the ownership of the resulting string to its caller.
Note that it would be unsafe if s was passed as an additional parameter to the function f as
it could escape this way and be mutated in the future – string_init would give up
ownership of s to pass it to f, and could not call unsafe_to_string safely.
We have provided the String.init[25.48], String.map[25.48] and String.mapi[25.48]
functions to cover most cases of building new strings. You should prefer those over
to_string or unsafe_to_string whenever applicable.
2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely
owned string and returns ownership back, so that we can mutate the sequence again after
the call ended.
In this use-case, we do not promise that s will never be mutated after the call to
bytes_length s. The String.length[25.48] function temporarily borrows unique
ownership of the byte sequence (and sees it as a string), but returns this ownership back to
the caller, which may assume that s is still a valid byte sequence after the call. Note that
this is only correct because we know that String.length[25.48] does not capture its
argument – it could escape by a side-channel such as a memoization combinator.
The caller may not mutate s while the string is borrowed (it has temporarily given up
ownership). This affects concurrent programs, but also higher-order functions: if
String.length[25.48] returned a closure to be called later, s should not be mutated until
this closure is fully applied and returns ownership.
The first declaration is incorrect, because the string literal "hello" could be shared by the
compiler with other parts of the program, and mutating incorrect is a bug. You must
always use the second version, which performs a copy and is thus correct.
Assuming unique ownership of strings that are not string literals, but are (partly) built from
string literals, is also incorrect. For example, mutating unsafe_of_string ("foo" ^ s)
could mutate the shared string "foo" – assuming a rope-like representation of strings. More
generally, functions operating on strings will assume shared ownership, they do not preserve
unique ownership. It is thus incorrect to assume unique ownership of the result of
unsafe_of_string.
The only case we have reasonable confidence is safe is if the produced bytes is shared –
used as an immutable byte sequence. This is possibly useful for incremental migration of
low-level programs that manipulate immutable sequences of bytes (for example
Marshal.from_bytes[25.31]) and previously used the string type for this purpose.
Since: 4.13.0
Iterators
val to_seq : t -> char Seq.t
Iterate on the string, in increasing index order. Modifications of the string during iteration
will be reflected in the sequence.
Since: 4.07
522
• Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by int
values sign-extend (resp. zero-extend) their result.
• Functions that encode 8-bit or 16-bit integers represented by int values truncate their input
to their least significant bytes.
val fill : bytes -> pos:int -> len:int -> char -> unit
fill s ~pos ~len c modifies s in place, replacing len characters with c, starting at pos.
Raises Invalid_argument if pos and len do not designate a valid range of s.
val blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
blit ~src ~src_pos ~dst ~dst_pos ~len copies len bytes from sequence src, starting at
index src_pos, to sequence dst, starting at index dst_pos. It works correctly even if src
and dst are the same byte sequence, and the source and destination intervals overlap.
Raises Invalid_argument if src_pos and len do not designate a valid range of src, or if
dst_pos and len do not designate a valid range of dst.
val blit_string :
src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
blit ~src ~src_pos ~dst ~dst_pos ~len copies len bytes from string src, starting at
index src_pos, to byte sequence dst, starting at index dst_pos.
Since: 4.05.0 in BytesLabels
Raises Invalid_argument if src_pos and len do not designate a valid range of src, or if
dst_pos and len do not designate a valid range of dst.
val iteri : f:(int -> char -> unit) -> bytes -> unit
Same as BytesLabels.iter[25.9], but the function is applied to the index of the byte as
first argument and the byte itself as second argument.
val mapi : f:(int -> char -> char) -> bytes -> bytes
mapi ~f s calls f with each character of s and its index (in increasing index order) and
stores the resulting bytes in a new sequence that is returned as the result.
val fold_left : f:('a -> char -> 'a) -> init:'a -> bytes -> 'a
fold_left f x s computes f (... (f (f x (get s 0)) (get s 1)) ...) (get s
(n-1)), where n is the length of s.
Since: 4.13.0
val fold_right : f:(char -> 'a -> 'a) -> bytes -> init:'a -> 'a
fold_right f s x computes f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x)
...)), where n is the length of s.
Since: 4.13.0
val index_from_opt : bytes -> int -> char -> int option
index_from_opt s i c returns the index of the first occurrence of byte c in s after
position i or None if c does not occur in s after position i. index_opt s c is equivalent to
index_from_opt s 0 c.
Since: 4.05
Raises Invalid_argument if i is not a valid position in s.
val rindex_from_opt : bytes -> int -> char -> int option
rindex_from_opt s i c returns the index of the last occurrence of byte c in s before
position i+1 or None if c does not occur in s before position i+1. rindex_opt s c is
equivalent to rindex_from s (length s - 1) c.
Since: 4.05
Raises Invalid_argument if i+1 is not a valid position in s.
type t = bytes
An alias for the type of byte sequences.
Unique ownership is linear: passing the data to another piece of code means giving up
ownership (we cannot write the data again). A unique owner may decide to make the data
shared (giving up mutation rights on it), but shared data may not become uniquely-owned
again.
unsafe_to_string s can only be used when the caller owns the byte sequence s – either
uniquely or as shared immutable data. The caller gives up ownership of s, and gains
ownership of the returned string.
There are two valid use-cases that respect this ownership discipline:
1. Creating a string by initializing and mutating a byte sequence that is never changed after
initialization is performed.
This function is safe because the byte sequence s will never be accessed or mutated after
unsafe_to_string is called. The string_init code gives up ownership of s, and returns
the ownership of the resulting string to its caller.
Note that it would be unsafe if s was passed as an additional parameter to the function f as
it could escape this way and be mutated in the future – string_init would give up
ownership of s to pass it to f, and could not call unsafe_to_string safely.
We have provided the String.init[25.48], String.map[25.48] and String.mapi[25.48]
functions to cover most cases of building new strings. You should prefer those over
to_string or unsafe_to_string whenever applicable.
2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely
owned string and returns ownership back, so that we can mutate the sequence again after
the call ended.
In this use-case, we do not promise that s will never be mutated after the call to
bytes_length s. The String.length[25.48] function temporarily borrows unique
ownership of the byte sequence (and sees it as a string), but returns this ownership back to
the caller, which may assume that s is still a valid byte sequence after the call. Note that
this is only correct because we know that String.length[25.48] does not capture its
argument – it could escape by a side-channel such as a memoization combinator.
The caller may not mutate s while the string is borrowed (it has temporarily given up
ownership). This affects concurrent programs, but also higher-order functions: if
String.length[25.48] returned a closure to be called later, s should not be mutated until
this closure is fully applied and returns ownership.
Chapter 25. The standard library 533
The first declaration is incorrect, because the string literal "hello" could be shared by the
compiler with other parts of the program, and mutating incorrect is a bug. You must
always use the second version, which performs a copy and is thus correct.
Assuming unique ownership of strings that are not string literals, but are (partly) built from
string literals, is also incorrect. For example, mutating unsafe_of_string ("foo" ^ s)
could mutate the shared string "foo" – assuming a rope-like representation of strings. More
generally, functions operating on strings will assume shared ownership, they do not preserve
unique ownership. It is thus incorrect to assume unique ownership of the result of
unsafe_of_string.
The only case we have reasonable confidence is safe is if the produced bytes is shared –
used as an immutable byte sequence. This is possibly useful for incremental migration of
low-level programs that manipulate immutable sequences of bytes (for example
Marshal.from_bytes[25.31]) and previously used the string type for this purpose.
Since: 4.13.0
534
Iterators
val to_seq : t -> char Seq.t
Iterate on the string, in increasing index order. Modifications of the string during iteration
will be reflected in the sequence.
Since: 4.07
• Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by int
values sign-extend (resp. zero-extend) their result.
• Functions that encode 8-bit or 16-bit integers represented by int values truncate their input
to their least significant bytes.
type t = char
An alias for the type of characters.
type t =
{ re : float ;
im : float ;
}
The type of complex numbers. re is the real part and im the imaginary part.
val zero : t
The complex number 0.
val one : t
The complex number 1.
val i : t
The complex number i.
Square root. The result x + i.y is such that x > 0 or x = 0 and y >= 0. This function
has a discontinuity along the negative real axis.
type t = string
The type of digests: 16-character strings.
val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t
map_left f e is Left (f v) if e is Left v and e if e is Right _.
val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t
map_right f e is Right (f v) if e is Right v and e if e is Left _.
val map :
left:('a1 -> 'a2) ->
right:('b1 -> 'b2) -> ('a1, 'b1) t -> ('a2, 'b2) t
Chapter 25. The standard library 543
map ~left ~right (Left v) is Left (left v), map ~left ~right (Right v) is Right
(right v).
val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c
fold ~left ~right (Left v) is left v, and fold ~left ~right (Right v) is right v.
val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit
iter ~left ~right (Left v) is left v, and iter ~left ~right (Right v) is right v.
val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool
for_all ~left ~right (Left v) is left v, and for_all ~left ~right (Right v) is
right v.
val equal :
left:('a -> 'a -> bool) ->
right:('b -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t -> bool
equal ~left ~right e0 e1 tests equality of e0 and e1 using left and right to
respectively compare values wrapped by Left _ and Right _.
val compare :
left:('a -> 'a -> int) ->
right:('b -> 'b -> int) -> ('a, 'b) t -> ('a, 'b) t -> int
compare ~left ~right e0 e1 totally orders e0 and e1 using left and right to
respectively compare values wrapped by Left _ and Right _. Left _ values are smaller
than Right _ values.
emptied from the ephemeron. The data could be alive for another reason and in that case the GC
will not free it, but the ephemeron will not hold the data anymore.
The ephemerons complicate the notion of liveness of values, because it is not anymore an
equivalence with the reachability from root value by usual pointers (not weak and not ephemerons).
With ephemerons the notion of liveness is constructed by the least fixpoint of: A value is alive if:
• it is a root value
• it is the data of an alive ephemeron with all its full keys alive
Notes:
• All the types defined in this module cannot be marshaled using output_value[24.2] or the
functions of the Marshal[25.31] module.
Ephemerons are defined in a language agnostic way in this paper: B. Hayes, Ephemerons: A
New Finalization Mechanism, OOPSLA’97
Since: 4.03.0
module type S =
sig
Propose the same interface as usual hash table. However since the bindings are weak, even if
mem h k is true, a subsequent find h k may raise Not_found because the garbage collector
can run between the two.
Moreover, the table shouldn’t be modified during a call to iter. Use filter_map_inplace
in this case.
include Hashtbl.S
val clean : 'a t -> unit
remove all dead bindings. Done automatically during automatic resizing.
end
include Hashtbl.SeededS
val clean : 'a t -> unit
remove all dead bindings. Done automatically during automatic resizing.
end
The output signature of the functor Ephemeron.K1.MakeSeeded[25.15] and
Ephemeron.K2.MakeSeeded[25.15].
module K1 :
sig
type ('k, 'd) t
an ephemeron with one key
module Make :
functor (H : Hashtbl.HashedType) -> Ephemeron.S with type key = H.t
Functor building an implementation of a weak hash table
module MakeSeeded :
functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key =
H.t
Chapter 25. The standard library 547
Functor building an implementation of a weak hash table. The seed is similar to the
one of Hashtbl.MakeSeeded[25.22].
end
module K2 :
sig
type ('k1, 'k2, 'd) t
an ephemeron with two keys
val blit_key1 : ('k1, 'a, 'b) t -> ('k1, 'c, 'd) t -> unit
Same as Ephemeron.K1.blit_key[25.15]
val blit_key2 : ('a, 'k2, 'b) t -> ('c, 'k2, 'd) t -> unit
Same as Ephemeron.K1.blit_key[25.15]
val blit_key12 : ('k1, 'k2, 'a) t -> ('k1, 'k2, 'b) t -> unit
Same as Ephemeron.K1.blit_key[25.15]
val blit_data : ('k1, 'k2, 'd) t -> ('k1, 'k2, 'd) t -> unit
Same as Ephemeron.K1.blit_data[25.15]
module Make :
functor (H1 : Hashtbl.HashedType) -> functor (H2 : Hashtbl.HashedType) ->
Ephemeron.S with type key = H1.t * H2.t
Functor building an implementation of a weak hash table
module MakeSeeded :
functor (H1 : Hashtbl.SeededHashedType) -> functor (H2 : Hashtbl.SeededHashedType)
-> Ephemeron.SeededS with type key = H1.t * H2.t
Functor building an implementation of a weak hash table. The seed is similar to the
one of Hashtbl.MakeSeeded[25.22].
Chapter 25. The standard library 549
end
module Kn :
sig
type ('k, 'd) t
an ephemeron with an arbitrary number of keys of the same type
val set_key : ('k, 'd) t -> int -> 'k -> unit
Same as Ephemeron.K1.set_key[25.15]
Same as Ephemeron.K1.unset_data[25.15]
module Make :
functor (H : Hashtbl.HashedType) -> Ephemeron.S with type key = H.t array
Functor building an implementation of a weak hash table
module MakeSeeded :
functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key =
H.t array
Functor building an implementation of a weak hash table. The seed is similar to the
one of Hashtbl.MakeSeeded[25.22].
end
module GenHashTable :
sig
Define a hash table on generic containers which have a notion of "death" and aliveness. If a
binding is dead the hash table can automatically remove it.
type equal =
| ETrue
| EFalse
| EDead
the container is dead
module MakeSeeded :
functor (H : sig
type t
keys
Functor building an implementation of an hash table that use the container for keeping
the information given
end
• name0 is the longest suffix of name that does not contain a directory separator;
• ext starts with a period;
• ext is preceded by at least one non-period character in name0.
If such a suffix does not exist, extension name is the empty string.
Since: 4.04
Return the given file name without its extension, as defined in Filename.extension[25.16].
If the extension is empty, the function returns the given file name.
The following invariant holds for any file name s:
remove_extension s ^ extension s = s
Since: 4.04
val open_temp_file :
?mode:open_flag list ->
?perms:int ->
?temp_dir:string -> string -> string -> string * out_channel
554
Same as Filename.temp_file[25.16], but returns both the name of a fresh temporary file,
and an output channel opened (atomically) on this file. This function is more secure than
temp_file: there is no risk that the temporary file will be modified (e.g. replaced by a
symbolic link) before the program opens it. The optional argument mode is a list of
additional flags to control the opening of the file. It can contain one or several of
Open_append, Open_binary, and Open_text. The default is [Open_text] (open in text
mode). The file is created with permissions perms (defaults to readable and writable only
by the file owner, 0o600).
Before 4.03.0 no ?perms optional argument
Before 3.11.2 no ?temp_dir optional argument
Raises Sys_error if the file could not be opened.
val quote_command :
string ->
?stdin:string -> ?stdout:string -> ?stderr:string -> string list -> string
quote_command cmd args returns a quoted command line, suitable for use as an argument
to Sys.command[25.50], Unix.system[27.1], and the Unix.open_process[27.1] functions.
The string cmd is the command to call. The list args is the list of arguments to pass to this
command. It can be empty.
Chapter 25. The standard library 555
The optional arguments ?stdin and ?stdout and ?stderr are file names used to redirect
the standard input, the standard output, or the standard error of the command. If
~stdin:f is given, a redirection < f is performed and the standard input of the command
reads from file f. If ~stdout:f is given, a redirection > f is performed and the standard
output of the command is written to file f. If ~stderr:f is given, a redirection 2> f is
performed and the standard error of the command is written to file f. If both ~stdout:f
and ~stderr:f are given, with the exact same file name f, a 2>&1 redirection is performed
so that the standard output and the standard error of the command are interleaved and
redirected to the same file f.
Under Unix and Cygwin, the command, the arguments, and the redirections if any are
quoted using Filename.quote[25.16], then concatenated. Under Win32, additional quoting
is performed as required by the cmd.exe shell that is called by Sys.command[25.50].
Since: 4.10.0
Raises Failure if the command cannot be escaped on the current platform.
Floating-point addition.
val pi : float
The constant pi.
Arc sine. The argument must fall within the range [-1.0, 1.0]. Result is in radians and is
between -pi/2 and pi/2.
type t = float
An alias for the type of floating-point numbers.
max_num x y returns the maximum of x and y treating nan as missing values. If both x and
y are nan nan is returned. Moreover max_num (-0.) (+0.) = +0.
Since: 4.08.0
module Array :
sig
type t = floatarray
The type of float arrays with packed representation.
Since: 4.08.0
val fill : t -> int -> int -> float -> unit
fill a pos len x modifies the floatarray a in place, storing x in elements number
pos to pos + len - 1.
Raises Invalid_argument if pos and len do not designate a valid subarray of a.
val blit : t -> int -> t -> int -> int -> unit
blit src src_pos dst dst_pos len copies len elements from floatarray src,
starting at element number src_pos, to floatarray dst, starting at element number
dst_pos. It works correctly even if src and dst are the same floatarray, and the
source and destination chunks overlap.
Raises Invalid_argument if src_pos and len do not designate a valid subarray of
src, or if dst_pos and len do not designate a valid subarray of dst.
Iterators
val iter : (float -> unit) -> t -> unit
iter f a applies function f in turn to all the elements of a. It is equivalent to f
a.(0); f a.(1); ...; f a.(length a - 1); ().
val iteri : (int -> float -> unit) -> t -> unit
Same as Float.Array.iter[25.17], but the function is applied with the index of the
element as first argument, and the element itself as second argument.
val fold_left : ('a -> float -> 'a) -> 'a -> t -> 'a
fold_left f x init computes f (... (f (f x init.(0)) init.(1)) ...)
init.(n-1), where n is the length of the floatarray init.
val fold_right : (float -> 'a -> 'a) -> t -> 'a -> 'a
fold_right f a init computes f a.(0) (f a.(1) ( ... (f a.(n-1) init)
...)), where n is the length of the floatarray a.
val map2 : (float -> float -> float) -> t -> t -> t
map2 f a b applies function f to all the elements of a and b, and builds a floatarray
with the results returned by f: [| f a.(0) b.(0); ...; f a.(length a - 1)
b.(length b - 1)|].
Raises Invalid_argument if the floatarrays are not the same size.
566
Array scanning
val for_all : (float -> bool) -> t -> bool
for_all f [|a1; ...; an|] checks if all elements of the floatarray satisfy the
predicate f. That is, it returns (f a1) && (f a2) && ... && (f an).
Sorting
val sort : (float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The
comparison function must return 0 if its arguments compare as equal, a positive integer
if the first is greater, and a negative integer if the first is smaller (see below for a
complete specification). For example, compare[24.2] is a suitable comparison function.
After calling sort, the array is sorted in place in increasing order. sort is guaranteed
to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a be the floatarray and cmp the
comparison function. The following must be true for all x, y, z in a :
• cmp x y > 0 if and only if cmp y x < 0
• if cmp x y ≥ 0 and cmp y z ≥ 0 then cmp x z ≥ 0
When sort returns, a contains the same elements as before, reordered in such a way
that for all i and j valid indices of a :
• cmp a.(i) a.(j) ≥ 0 if and only if i ≥ j
val stable_sort : (float -> float -> int) -> t -> unit
Same as Float.Array.sort[25.17], but the sorting algorithm is stable (i.e. elements
that compare equal are kept in their original order) and not guaranteed to run in
constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length
n/2, where n is the length of the floatarray. It is usually faster than the current
implementation of Float.Array.sort[25.17].
Chapter 25. The standard library 567
val fast_sort : (float -> float -> int) -> t -> unit
Same as Float.Array.sort[25.17] or Float.Array.stable_sort[25.17], whichever is
faster on typical input.
end
Float arrays with packed representation.
module ArrayLabels :
sig
type t = floatarray
The type of float arrays with packed representation.
Since: 4.08.0
val fill : t -> pos:int -> len:int -> float -> unit
fill a ~pos ~len x modifies the floatarray a in place, storing x in elements number
pos to pos + len - 1.
Raises Invalid_argument if pos and len do not designate a valid subarray of a.
Chapter 25. The standard library 569
Iterators
val iter : f:(float -> unit) -> t -> unit
iter ~f a applies function f in turn to all the elements of a. It is equivalent to f
a.(0); f a.(1); ...; f a.(length a - 1); ().
val iteri : f:(int -> float -> unit) -> t -> unit
Same as Float.ArrayLabels.iter[25.17], but the function is applied with the index of
the element as first argument, and the element itself as second argument.
val fold_left : f:('a -> float -> 'a) -> init:'a -> t -> 'a
fold_left ~f x ~init computes f (... (f (f x init.(0)) init.(1)) ...)
init.(n-1), where n is the length of the floatarray init.
val fold_right : f:(float -> 'a -> 'a) -> t -> init:'a -> 'a
fold_right f a init computes f a.(0) (f a.(1) ( ... (f a.(n-1) init)
...)), where n is the length of the floatarray a.
570
Array scanning
val for_all : f:(float -> bool) -> t -> bool
for_all ~f [|a1; ...; an|] checks if all elements of the floatarray satisfy the
predicate f. That is, it returns (f a1) && (f a2) && ... && (f an).
Sorting
val sort : cmp:(float -> float -> int) -> t -> unit
Sort a floatarray in increasing order according to a comparison function. The
comparison function must return 0 if its arguments compare as equal, a positive integer
if the first is greater, and a negative integer if the first is smaller (see below for a
complete specification). For example, compare[24.2] is a suitable comparison function.
Chapter 25. The standard library 571
After calling sort, the array is sorted in place in increasing order. sort is guaranteed
to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space.
Specification of the comparison function: Let a be the floatarray and cmp the
comparison function. The following must be true for all x, y, z in a :
• cmp x y > 0 if and only if cmp y x < 0
• if cmp x y ≥ 0 and cmp y z ≥ 0 then cmp x z ≥ 0
When sort returns, a contains the same elements as before, reordered in such a way
that for all i and j valid indices of a :
• cmp a.(i) a.(j) ≥ 0 if and only if i ≥ j
val stable_sort : cmp:(float -> float -> int) -> t -> unit
Same as Float.ArrayLabels.sort[25.17], but the sorting algorithm is stable (i.e.
elements that compare equal are kept in their original order) and not guaranteed to
run in constant heap space.
The current implementation uses Merge Sort. It uses a temporary floatarray of length
n/2, where n is the length of the floatarray. It is usually faster than the current
implementation of Float.ArrayLabels.sort[25.17].
val fast_sort : cmp:(float -> float -> int) -> t -> unit
Same as Float.ArrayLabels.sort[25.17] or Float.ArrayLabels.stable_sort[25.17],
whichever is faster on typical input.
end
Float arrays with packed representation (labeled functions).
Introduction
You may consider this module as providing an extension to the printf facility to provide automatic
line splitting. The addition of pretty-printing annotations to your regular printf format strings
gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the
documentation of the function Format.fprintf[25.18].
You may also use the explicit pretty-printing box management and printing functions provided
by this module. This style is more basic but more verbose than the concise fprintf format strings.
For instance, the sequence open_box 0; print_string "x ="; print_space (); print_int
1; close_box (); print_newline () that prints x = 1 within a pretty-printing box, can be
abbreviated as printf "@[%s@ %i@]@." "x =" 1, or even shorter printf "@[x =@ %i@]@." 1.
Rule of thumb for casual users of this library:
• use simple pretty-printing boxes (as obtained by open_box 0);
• use simple break hints as obtained by print_cut () that outputs a simple break hint, or by
print_space () that outputs a space indicating a break hint;
Chapter 25. The standard library 573
• once a pretty-printing box is open, display its material with basic printing functions (e. g.
print_int and print_string);
• when the material for a pretty-printing box has been printed, call close_box () to close the
box;
• at the end of pretty-printing, flush the pretty-printer to display all the remaining material,
e.g. evaluate print_newline ().
Formatters
type formatter
Abstract data corresponding to a pretty-printer (also called a formatter) and all its
machinery. See also [25.18].
Pretty-printing boxes
The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive inden-
tation and line splitting behavior of the pretty-printer.
Each different pretty-printing box kind introduces a specific line splitting policy:
• within an horizontal box, break hints never split the line (but the line may be split in a box
nested deeper),
• within an horizontal/vertical box, if the box fits on the current line then break hints never
split the line, otherwise break hint always split the line,
• within a compacting box, a break hint never splits the line, unless there is no more room on
the current line.
574
Note that line splitting policy is box specific: the policy of a box does not rule the policy of
inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within
the vertical box will split the line.
Moreover, opening a box after the maximum indentation limit[25.18] splits the line whether or
not the box would end up fitting on the line.
val pp_open_box : formatter -> int -> unit
val open_box : int -> unit
pp_open_box ppf d opens a new compacting pretty-printing box with offset d in the
formatter ppf.
Within this box, the pretty-printer prints as much as possible material on every line.
A break hint splits the line if there is no more room on the line to print the remainder of
the box.
Within this box, the pretty-printer emphasizes the box structure: if a structural box does
not fit fully on a simple line, a break hint also splits the line if the splitting “moves to the
left” (i.e. the new line gets an indentation smaller than the one of the current line).
This box is the general purpose pretty-printing box.
If the pretty-printer splits the line in the box, offset d is added to the current indentation.
Formatting functions
val pp_print_string : formatter -> string -> unit
val print_string : string -> unit
pp_print_string ppf s prints s in the current pretty-printing box.
Break hints
A ’break hint’ tells the pretty-printer to output some space or split the line whichever way is more
appropriate to the current pretty-printing box splitting rules.
Break hints are used to separate printing items and are mandatory to let the pretty-printer
correctly split lines and indent items.
Simple break hints are:
Note: the notions of space and line splitting are abstract for the pretty-printing engine, since
those notions can be completely redefined by the programmer. However, in the pretty-printer
default setting, “output a space” simply means printing a space character (ASCII code 32) and
“split the line” means printing a newline character (ASCII code 10).
val pp_print_space : formatter -> unit -> unit
val print_space : unit -> unit
pp_print_space ppf () emits a ’space’ break hint: the pretty-printer may split the line at
this point, otherwise it prints one space.
pp_print_space ppf () is equivalent to pp_print_break ppf 1 0.
val pp_print_custom_break :
formatter ->
fits:string * int * string -> breaks:string * int * string -> unit
Chapter 25. The standard library 577
[
a;
b;
c;
]
Since: 4.08.0
Pretty-printing termination
val pp_print_flush : formatter -> unit -> unit
val print_flush : unit -> unit
End of pretty-printing: resets the pretty-printer to initial state.
All open pretty-printing boxes are closed, all pending text is printed. In addition, the
pretty-printer low level output device is flushed to ensure that all pending text is really
displayed.
Note: never use print_flush in the normal course of a pretty-printing routine, since the
pretty-printer uses a complex buffering machinery to properly indent the output; manually
flushing those buffers at random would conflict with the pretty-printer strategy and result
to poor rendering.
Only consider using print_flush when displaying all pending material is mandatory (for
instance in case of interactive use when you want the user to read some text) and when
resetting the pretty-printer state will not disturb further pretty-printing.
Warning: If the output device of the pretty-printer is an output channel, repeated calls to
print_flush means repeated calls to flush[24.2] to flush the out channel; these explicit
flush calls could foil the buffering strategy of output channels and could dramatically impact
efficiency.
Margin
val pp_set_margin : formatter -> int -> unit
val set_margin : int -> unit
pp_set_margin ppf d sets the right margin to d (in characters): the pretty-printer splits
lines that overflow the right margin according to the break hints given. Setting the margin
to d means that the formatting engine aims at printing at most d-1 characters per line.
Nothing happens if d is smaller than 2. If d is too large, the right margin is set to the
maximum admissible value (which is greater than 10 ^ 9). If d is less than the current
maximum indentation limit, the maximum indentation limit is decreased while trying to
preserve a minimal ratio max_indent/margin>=50% and if possible the current difference
margin - max_indent.
See also Format.pp_set_geometry[25.18].
Chapter 25. The standard library 579
123456
789A
because the nested box "@[7@]" is opened after the maximum indentation limit (7>5)
and its parent box does not fit on the current line. Either decreasing the length of the
parent box to make it fit on a line:
printf "@[123456@[7@]89@]@."
or opening an intermediary box before the maximum indentation limit which fits on the
current line
printf "@[123@[456@[7@]89@]A@]@."
avoids the rejection to the left of the inner boxes and print respectively "123456789" and
"123456789A" . Note also that vertical boxes never fit on a line whereas horizontal boxes
always fully fit on the current line. Opening a box may split a line whereas the contents
may have fit. If this behavior is problematic, it can be curtailed by setting the maximum
indentation limit to margin - 1. Note that setting the maximum indentation limit to
margin is invalid.
Nothing happens if d is smaller than 2.
If d is too large, the limit is set to the maximum admissible value (which is greater than 10
^ 9).
If d is greater or equal than the current margin, it is ignored, and the current maximum
indentation limit is kept.
See also Format.pp_set_geometry[25.18].
Geometry
Geometric functions can be used to manipulate simultaneously the coupled variables, margin and
maxixum indentation limit.
type geometry =
{ max_indent : int ;
margin : int ;
}
val check_geometry : geometry -> bool
Check if the formatter geometry is valid: 1 < max_indent < margin
Tabulation boxes
A tabulation box prints material on lines divided into cells of fixed length. A tabulation box provides
a simple way to display vertical columns of left adjusted text.
This box features command set_tab to define cell boundaries, and command print_tab to
move from cell to cell and split the line when there is no more cells to print on the line.
Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabula-
tion box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of
columns within module Format[25.18].
val pp_open_tbox : formatter -> unit -> unit
val open_tbox : unit -> unit
open_tbox () opens a new tabulation box.
This box prints lines separated into cells of fixed width.
Inside a tabulation box, special tabulation markers defines points of interest on the line (for
instance to delimit cell boundaries). Function Format.set_tab[25.18] sets a tabulation
marker at insertion point.
A tabulation box features specific tabulation breaks to move to next tabulation marker or
split the line. Function Format.print_tbreak[25.18] prints a tabulation break.
Ellipsis
val pp_set_ellipsis_text : formatter -> string -> unit
val set_ellipsis_text : string -> unit
Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single
dot, ., by default).
Semantic tags
type stag = ..
Semantic tags (or simply tags) are user’s defined annotations to associate user’s specific
operations to printed entities.
Common usage of semantic tags is text decoration to get specific font or text size
rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX
elements or terminal escape sequences). More sophisticated usage of semantic tags
Chapter 25. The standard library 583
could handle dynamic modification of the pretty-printer behavior to properly print the
material within some specific tags. For instance, we can define an RGB tag like so:
In order to properly delimit printed entities, a semantic tag must be opened before and
closed after the entity. Semantic tags must be properly nested like parentheses using
Format.pp_open_stag[25.18] and Format.pp_close_stag[25.18].
Tag specific operations occur any time a tag is opened or closed, At each occurrence, two
kinds of operations are performed tag-marking and tag-printing:
• The tag-marking operation is the simpler tag specific operation: it simply writes a tag
specific string into the output device of the formatter. Tag-marking does not interfere
with line-splitting computation.
• The tag-printing operation is the more involved tag specific operation: it can print
arbitrary material to the formatter. Tag-printing is tightly linked to the current
pretty-printer operations.
Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the
rendering device, while tag-printing allows fine tuning of printing routines to print the same
entity differently according to the semantic tags (i.e. print additional material or even omit
parts of the output).
More precisely: when a semantic tag is opened or closed then both and successive
’tag-printing’ and ’tag-marking’ operations occur:
Being written directly into the output device of the formatter, semantic tag marker strings
are not considered as part of the printing material that drives line splitting (in other words,
the length of the strings corresponding to tag markers is considered as zero for line splitting).
Thus, semantic tag handling is in some sense transparent to pretty-printing and does not
interfere with usual indentation. Hence, a single pretty-printing routine can output both
simple ’verbatim’ material or richer decorated output depending on the treatment of tags.
By default, tags are not active, hence the output is not decorated with tag information.
Once set_tags is set to true, the pretty-printer engine honors tags and decorates the
output accordingly.
584
Default tag-marking functions behave the HTML way: string tags[25.18] are enclosed in "<"
and ">" while other tags are ignored; hence, opening marker for tag string "t" is "<t>" and
closing marker is "</t>".
Default tag-printing functions just do nothing.
Tag-marking and tag-printing functions are user definable and can be set by calling
Format.set_formatter_stag_functions[25.18].
Semantic tag operations may be set on or off with Format.set_tags[25.18]. Tag-marking
operations may be set on or off with Format.set_mark_tags[25.18]. Tag-printing
operations may be set on or off with Format.set_print_tags[25.18].
Since: 4.08.0
val pp_set_formatter_output_functions :
formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
val set_formatter_output_functions :
(string -> int -> int -> unit) -> (unit -> unit) -> unit
pp_set_formatter_output_functions ppf out flush redirects the standard
pretty-printer output functions to the functions out and flush.
The out function performs all the pretty-printer string 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 (via conversion %!, or
pretty-printing indications @? or @., or using low level functions print_flush or
print_newline).
val pp_get_formatter_output_functions :
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
val get_formatter_output_functions :
unit -> (string -> int -> int -> unit) * (unit -> unit)
Return the current output functions of the standard pretty-printer.
586
• the out_string function performs all the pretty-printer string 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 out_flush function flushes the pretty-printer output device.
• out_newline is called to open a new line when the pretty-printer splits the line.
• the out_spaces function outputs spaces when a break hint leads to spaces instead of a
line split. It is called with the number of spaces to output.
• the out_indent function performs new line indentation when the pretty-printer splits
the line. It is called with the indentation value of the new line.
By default:
Since: 4.01.0
val pp_set_formatter_out_functions :
formatter -> formatter_out_functions -> unit
val set_formatter_out_functions : formatter_out_functions -> unit
Chapter 25. The standard library 587
val pp_get_formatter_out_functions :
formatter -> unit -> formatter_out_functions
val get_formatter_out_functions : unit -> formatter_out_functions
Return the current output functions of the pretty-printer, including line splitting and
indentation functions. Useful to record the current setting and restore it afterwards.
Since: 4.01.0
val pp_set_formatter_stag_functions :
formatter -> formatter_stag_functions -> unit
val set_formatter_stag_functions : formatter_stag_functions -> unit
pp_set_formatter_stag_functions ppf tag_funs changes the meaning of opening and
closing semantic tag operations to use the functions in tag_funs when printing on ppf.
When opening a semantic tag with name t, the string t is passed to the opening
tag-marking function (the mark_open_stag field of the record tag_funs), that must return
the opening tag marker for that name. When the next call to close_stag () happens, the
semantic tag name t is sent back to the closing tag-marking function (the mark_close_stag
field of record tag_funs), that must return a closing tag marker for that name.
588
The print_ field of the record contains the tag-printing functions that are called at tag
opening and tag closing time, to output regular material in the pretty-printer queue.
Since: 4.08.0
val pp_get_formatter_stag_functions :
formatter -> unit -> formatter_stag_functions
val get_formatter_stag_functions : unit -> formatter_stag_functions
Return the current semantic tag operation functions of the standard pretty-printer.
Since: 4.08.0
Defining formatters
Defining new formatters permits unrelated output of material in parallel on several output devices.
All the parameters of a formatter are local to the formatter: right margin, maximum indentation
limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are
specific to each formatter and may be fixed independently.
For instance, given a Buffer.t[25.7] buffer b, Format.formatter_of_buffer[25.18] b returns
a new formatter using buffer b as its output device. Similarly, given a out_channel[24.2] output
channel oc, Format.formatter_of_out_channel[25.18] oc returns a new formatter using channel
oc as its output device.
Alternatively, given out_funs, a complete set of output functions for a formatter, then
Format.formatter_of_out_functions[25.18] out_funs computes a new formatter using those
functions for output.
val formatter_of_out_channel : out_channel -> formatter
formatter_of_out_channel oc returns a new formatter writing to the corresponding
output channel oc.
val make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter
make_formatter out flush returns a new formatter that outputs with function out, and
flushes with function flush.
For instance,
make_formatter
(Stdlib.output oc)
(fun () -> Stdlib.flush oc)
returns a formatter to the out_channel[24.2] oc.
Symbolic pretty-printing
Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs
symbolic pretty-printing items.
When using a symbolic formatter, all regular pretty-printing activities occur but output material
is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output
buffer allows post-processing of symbolic output before performing low level output operations.
In practice, first define a symbolic output buffer b using:
Use symbolic formatter ppf as usual, and retrieve symbolic items at end of pretty-printing by
flushing symbolic output buffer sob with:
• flush_symbolic_output_buffer sob.
590
type symbolic_output_item =
| Output_flush
symbolic flush command
| Output_newline
symbolic newline command
| Output_string of string
Output_string s: symbolic output for string s
| Output_spaces of int
Output_spaces n: symbolic command to output n spaces
| Output_indent of int
Output_indent i: symbolic indentation of size i
Items produced by symbolic pretty-printers
Since: 4.06.0
type symbolic_output_buffer
The output buffer of a symbolic pretty-printer.
Since: 4.06.0
val get_symbolic_output_buffer :
symbolic_output_buffer -> symbolic_output_item list
get_symbolic_output_buffer sob returns the contents of buffer sob.
Since: 4.06.0
val flush_symbolic_output_buffer :
symbolic_output_buffer -> symbolic_output_item list
flush_symbolic_output_buffer sob returns the contents of buffer sob and resets buffer
sob. flush_symbolic_output_buffer sob is equivalent to let items =
get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items
Since: 4.06.0
val add_symbolic_output_item :
symbolic_output_buffer -> symbolic_output_item -> unit
Chapter 25. The standard library 591
val pp_print_seq :
?pp_sep:(formatter -> unit -> unit) ->
(formatter -> 'a -> unit) ->
formatter -> 'a Seq.t -> unit
pp_print_seq ?pp_sep pp_v ppf s prints items of sequence s, using pp_v to print each
item, and calling pp_sep between items (pp_sep defaults to Format.pp_print_cut[25.18].
Does nothing on empty sequences.
This function does not terminate on infinite sequences.
Since: 4.12
val pp_print_option :
?none:(formatter -> unit -> unit) ->
(formatter -> 'a -> unit) -> formatter -> 'a option -> unit
pp_print_option ?none pp_v ppf o prints o on ppf using pp_v if o is Some v and none if
it is None. none prints nothing by default.
Since: 4.08
val pp_print_result :
ok:(formatter -> 'a -> unit) ->
error:(formatter -> 'e -> unit) ->
formatter -> ('a, 'e) result -> unit
592
val pp_print_either :
left:(formatter -> 'a -> unit) ->
right:(formatter -> 'b -> unit) ->
formatter -> ('a, 'b) Either.t -> unit
pp_print_either ~left ~right ppf e prints e on ppf using left if e is Either.Left
_ and right if e is Either.Right _.
Since: 4.13
Formatted pretty-printing
Module Format provides a complete set of printf like functions for pretty-printing using format
string specifications.
Specific annotations may be added in the format strings to give pretty-printing commands to
the pretty-printing engine.
Those annotations are introduced in the format strings using the @ character. For instance, @
means a space break, @, means a cut, @[ opens a new box, and @] closes the last open box.
val fprintf : formatter -> ('a, formatter, unit) format -> 'a
fprintf ff fmt arg1 ... argN formats the arguments arg1 to argN according to the format
string fmt, and outputs the resulting string on the formatter ff.
The format string fmt is a character string which contains three types of objects: plain char-
acters and conversion specifications as specified in the Printf[25.38] module, and pretty-printing
indications specific to the Format module.
The pretty-printing indication characters are introduced by a @ character, and their meanings
are:
• @[: open a pretty-printing box. The type and offset of the box may be optionally specified with
the following syntax: the < character, followed by an optional box type indication, then an
optional integer offset, and the closing > character. Pretty-printing box type is one of h, v, hv,
b, or hov. ’h’ stands for an ’horizontal’ pretty-printing box, ’v’ stands for a ’vertical’ pretty-
printing box, ’hv’ stands for an ’horizontal/vertical’ pretty-printing box, ’b’ stands for an
’horizontal-or-vertical’ pretty-printing box demonstrating indentation, ’hov’ stands a simple
’horizontal-or-vertical’ pretty-printing box. For instance, @[<hov 2> opens an ’horizontal-or-
vertical’ pretty-printing box with indentation 2 as obtained with open_hovbox 2. For more
details about pretty-printing boxes, see the various box opening functions open_*box.
• @;: output a ’full’ break hint as with print_break. The nspaces and offset parameters
of the break hint may be optionally specified with the following syntax: the < character,
followed by an integer nspaces value, then an integer offset, and a closing > character. If
no parameters are provided, the good break defaults to a ’space’ break hint.
• @.: flush the pretty-printer and split the line, as with print_newline ().
• @<n>: print the following item as if it were of length n. Hence, printf "@<0>%s" arg prints
arg as a zero length string. If @<n> is not followed by a conversion specification, then the
following character of the format is printed as if it were of length n.
• @{: open a semantic tag. The name of the tag may be optionally specified with the follow-
ing syntax: the < character, followed by an optional string specification, and the closing >
character. The string specification is any character string that does not contain the closing
character '>'. If omitted, the tag name defaults to the empty string. For more details about
semantic tags, see the functions Format.open_stag[25.18] and Format.close_stag[25.18].
• @?: flush the pretty-printer as with print_flush (). This is equivalent to the conversion %!.
• @\n: force a newline, as with force_newline (), not the normal way of pretty-printing, you
should prefer using break hints inside a vertical pretty-printing box.
Note: To prevent the interpretation of a @ character as a pretty-printing indication, escape it
with a % character. Old quotation mode @@ is deprecated since it is not compatible with formatted
input interpretation of character '@'.
Example: printf "@[%s@ %d@]@." "x =" 1 is equivalent to open_box (); print_string
"x ="; print_space (); print_int 1; close_box (); print_newline (). It prints x = 1
within a pretty-printing ’horizontal-or-vertical’ box.
val printf : ('a, formatter, unit) format -> 'a
Same as fprintf above, but output on std_formatter.
Same as printf above, but instead of printing on a formatter, returns a string containing
the result of formatting the arguments. The type of asprintf is general enough to interact
nicely with %a conversions.
Since: 4.01.0
val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a
Same as Format.fprintf[25.18], except the formatter is the last argument. dprintf "..."
a b c is a function of type formatter -> unit which can be given to a format specifier %t.
This can be used as a replacement for Format.asprintf[25.18] to delay formatting
decisions. Using the string returned by Format.asprintf[25.18] in a formatting context
forces formatting decisions to be taken in isolation, and the final string may be created
prematurely. Format.dprintf[25.18] allows delay of formatting decisions until the final
formatting context is known. For example:
Since: 4.08.0
val ifprintf : formatter -> ('a, formatter, unit) format -> 'a
Same as fprintf above, but does not print anything. Useful to ignore some material when
conditionally printing.
Since: 3.10.0
val kdprintf :
((formatter -> unit) -> 'a) ->
('b, formatter, unit, 'a) format4 -> 'b
Same as Format.dprintf[25.18] above, but instead of returning immediately, passes the
suspended printer to its first argument at the end of printing.
Since: 4.08.0
val ikfprintf :
(formatter -> 'a) ->
formatter -> ('b, formatter, unit, 'a) format4 -> 'b
Chapter 25. The standard library 595
Same as kfprintf above, but does not print anything. Useful to ignore some material when
conditionally printing.
Since: 3.12.0
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
Same as sprintf above, but instead of returning the string, passes it to the first argument.
val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b
Same as asprintf above, but instead of returning the string, passes it to the first argument.
Since: 4.03
Deprecated
val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a
Deprecated. This function is error prone. Do not use it. This function is neither
compositional nor incremental, since it flushes the pretty-printer queue at each call.
If you need to print to some buffer b, you must first define a formatter writing to b, using
let to_b = formatter_of_buffer b; then use regular calls to Format.fprintf with
formatter to_b.
val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
Deprecated. An alias for ksprintf.
val set_all_formatter_output_functions :
out:(string -> int -> int -> unit) ->
flush:(unit -> unit) ->
newline:(unit -> unit) -> spaces:(int -> unit) -> unit
Deprecated. Subsumed by set_formatter_out_functions.
val get_all_formatter_output_functions :
unit ->
(string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
(int -> unit)
Deprecated. Subsumed by get_formatter_out_functions.
val pp_set_all_formatter_output_functions :
formatter ->
out:(string -> int -> int -> unit) ->
flush:(unit -> unit) ->
newline:(unit -> unit) -> spaces:(int -> unit) -> unit
Deprecated. Subsumed by pp_set_formatter_out_functions.
596
val pp_get_all_formatter_output_functions :
formatter ->
unit ->
(string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
(int -> unit)
Deprecated. Subsumed by pp_get_formatter_out_functions.
String tags
val pp_open_tag : formatter -> tag -> unit
Deprecated. Subsumed by Format.pp_open_stag[25.18].
type formatter_tag_functions =
{ mark_open_tag : tag -> string ;
mark_close_tag : tag -> string ;
print_open_tag : tag -> unit ;
print_close_tag : tag -> unit ;
}
Deprecated. Subsumed by Format.formatter_stag_functions[25.18].
val pp_set_formatter_tag_functions :
formatter -> formatter_tag_functions -> unit
Deprecated. Subsumed by Format.pp_set_formatter_stag_functions[25.18].This
function will erase non-string tag formatting functions.
val pp_get_formatter_tag_functions :
formatter -> unit -> formatter_tag_functions
Deprecated. Subsumed by Format.pp_get_formatter_stag_functions[25.18].
Combinators
val id : 'a -> 'a
id is the identity function. For any argument x, id x is x.
val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c
flip f reverses the argument order of the binary function f. For any arguments x and y,
(flip f) x y is f y x.
Exception handling
val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a
protect ~finally work invokes work () and then finally () before work () returns
with its value or an exception. In the latter case the exception is re-raised after finally
(). If finally () raises an exception, then the exception Fun.Finally_raised[25.19] is
raised instead.
protect can be used to enforce local invariants whether work () returns normally or raises
an exception. However, it does not protect against unexpected exceptions raised inside
finally () such as Out_of_memory[24.2], Stack_overflow[24.2], or asynchronous
exceptions raised by signal handlers (e.g. Sys.Break[25.50]).
Note: It is a programming error if other kinds of exceptions are raised by finally, as any
exception raised in work () will be lost in the event of a Fun.Finally_raised[25.19]
exception. Therefore, one should make sure to handle those inside the finally.
type stat =
{ minor_words : float ;
Number of words allocated in the minor heap since the program was started.
promoted_words : float ;
Number of words allocated in the minor heap that survived a minor collection and
were moved to the major heap since the program was started.
major_words : float ;
Number of words allocated in the major heap, including the promoted words, since
the program was started.
minor_collections : int ;
Number of minor collections since the program was started.
major_collections : int ;
Number of major collection cycles completed since the program was started.
heap_words : int ;
Total size of the major heap, in words.
heap_chunks : int ;
Number of contiguous pieces of memory that make up the major heap.
live_words : int ;
Number of words of live data in the major heap, including the header words.
live_blocks : int ;
Number of live blocks in the major heap.
free_words : int ;
Number of words in the free list.
free_blocks : int ;
Number of blocks in the free list.
largest_free : int ;
Size (in words) of the largest block in the free list.
fragments : int ;
Number of wasted words due to fragmentation. These are 1-words free blocks placed
between two live blocks. They are not available for allocation.
compactions : int ;
Number of heap compactions since the program was started.
Chapter 25. The standard library 599
top_heap_words : int ;
Maximum size reached by the major heap, in words.
stack_size : int ;
Current size of the stack, in words.
Since: 3.12.0
forced_major_collections : int ;
Number of forced full major collections completed since the program was started.
Since: 4.12.0
}
The memory management counters are returned in a stat record.
The total amount of memory allocated by the program since it was started 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 ;
The size (in words) of the minor heap. Changing this parameter will trigger a minor
collection. Default: 256k.
mutable major_heap_increment : int ;
How much to add to the major heap when increasing it. If this number is less than or
equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will
double the heap size at each increase). If it is more than 1000, it is a fixed number of
words that will be added to the heap. Default: 15.
mutable space_overhead : int ;
The major GC speed is computed from this parameter. This is the memory that will
be "wasted" because the GC does not immediately collect unreachable blocks. It is
expressed as a percentage of the memory used for live data. The GC will work more
(use more CPU time and collect blocks more eagerly) if space_overhead is smaller.
Default: 120.
mutable verbose : int ;
This value controls the GC messages on standard error output. It is a sum of some of
the following flags, to print messages on the corresponding events:
• 0 is the next-fit policy, which is usually fast but can result in fragmentation,
increasing memory consumption.
• 1 is the first-fit policy, which avoids fragmentation but has corner cases (in
certain realistic workloads) where it is sensibly slower.
The size of the window used by the major GC for smoothing out variations in its
workload. This is an integer between 1 and 50. Default: 1.
Since: 4.03.0
custom_major_ratio : int ;
Target ratio of floating garbage to major heap size for out-of-heap memory held by
custom values located in the major heap. The GC speed is adjusted to try to use this
much memory for dead values that are not yet collected. Expressed as a percentage of
major heap size. The default value keeps the out-of-heap floating garbage about the
same size as the in-heap overhead. Note: this only applies to values allocated with
caml_alloc_custom_mem (e.g. bigarrays). Default: 44.
Since: 4.08.0
custom_minor_ratio : int ;
Bound on floating garbage for out-of-heap memory held by custom values in the
minor heap. A minor GC is triggered when this much memory is held by custom
values located in the minor heap. Expressed as a percentage of minor heap size. Note:
this only applies to values allocated with caml_alloc_custom_mem (e.g. bigarrays).
Default: 100.
Since: 4.08.0
custom_minor_max_size : int ;
Maximum amount of out-of-heap memory for each custom value allocated in the
minor heap. When a custom value is allocated on the minor heap and holds more than
this many bytes, only this value is counted against custom_minor_ratio and the rest
is directly counted against custom_major_ratio. Note: this only applies to values
allocated with caml_alloc_custom_mem (e.g. bigarrays). Default: 8192 bytes.
Since: 4.08.0
}
The GC parameters are given as a control record. Note that these parameters can also be
initialised by setting the OCAMLRUNPARAM environment variable. See the
documentation of ocamlrun.
Return the current size of the free space inside the minor heap.
Since: 4.03.0
Instead you should make sure that v is not in the closure of the finalisation function by
writing:
The f function can use all features of OCaml, including assignments that make the value
reachable again. It can also loop forever (in this case, the other finalisation functions will
not be called during the execution of f, unless it calls finalise_release). It can call
finalise on v or other values to register other functions or even itself. It can raise an
exception; in this case the exception will interrupt whatever the program was doing when
the function was called.
finalise will raise Invalid_argument if v is not guaranteed to be heap-allocated. Some
examples of values that are not heap-allocated are integers, constant constructors, booleans,
the empty array, the empty list, the unit value. The exact list of what is heap-allocated or
not is implementation-dependent. Some constant values can be heap-allocated but never
deallocated during the lifetime of the program, for example a list of integer constants; this is
also implementation-dependent. Note that values of types float are sometimes allocated
and sometimes not, so finalising them is unsafe, and finalise will also raise
Invalid_argument for them. Values of type 'a Lazy.t (for any 'a) are like float in this
respect, except that the compiler sometimes optimizes them in a way that prevents
finalise from detecting them. In this case, it will not raise Invalid_argument, but you
should still avoid calling finalise on lazy values.
The results of calling String.make[25.48], Bytes.make[25.8], Bytes.create[25.8],
Array.make[25.2], and ref[24.2] are guaranteed to be heap-allocated and non-constant
except when the length argument is 0.
type alarm
An alarm is a piece of data that calls a user function at the end of each major GC cycle.
The following functions are provided to create and delete alarms.
module Memprof :
sig
type allocation_source =
| Normal
| Marshal
| Custom
type allocation = private
{ n_samples : int ;
The number of samples in this block (≥ 1).
size : int ;
The size of the block, in words, excluding the header.
source : allocation_source ;
The type of the allocation.
callstack : Printexc.raw_backtrace ;
The callstack for the allocation.
}
The type of metadata associated with allocations. This is the type of records passed to
the callback triggered by the sampling of an allocation.
val start :
sampling_rate:float ->
?callstack_size:int -> ('minor, 'major) tracker -> unit
Start the sampling with the given parameters. Fails if sampling is already active.
The parameter sampling_rate is the sampling rate in samples per word (including
headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on
performance, and 1e-3 causes the program to run a few percent slower
The parameter callstack_size is the length of the callstack recorded at every
sample. Its default is max_int.
The parameter tracker determines how to track sampled blocks over their lifetime in
the minor and major heap.
Sampling is temporarily disabled when calling a callback for the current thread. So
they do not need to be re-entrant if the program is single-threaded. However, if
threads are used, it is possible that a context switch occurs during a callback, in this
case the callback functions must be re-entrant.
Note that the callback can be postponed slightly after the actual event. The callstack
passed to the callback is always accurate, but the program state may have evolved.
end
Memprof is a sampling engine for allocated memory words. Every allocated word has a
probability of being sampled equal to a configurable sampling rate. Once a block is
sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is
allocated, promoted or deallocated.
Since blocks are composed of several words, a block can potentially be sampled several
times. If a block is sampled several times, then each of the callback is called once for each
event of this block: the multiplicity is given in the n_samples field of the allocation
structure.
This engine makes it possible to implement a low-overhead memory profiler as an OCaml
library.
Note: this API is EXPERIMENTAL. It may change without prior notice.
One should notice that the use of the parser keyword and associated notation for streams are
only available through camlp4 extensions. This means that one has to preprocess its sources e. g.
by using the "-pp" command-line switch of the compilers.
type token =
| Kwd of string
| Ident of string
| Int of int
| Float of float
| String of string
608
| 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
Stream.Error[25.47] with the offending lexeme as its parameter) otherwise. Blanks and
newlines are skipped. Comments delimited by (* and *) are skipped as well, and can be
nested. A Stream.Failure[25.47] exception is raised if end of stream is unexpectedly
reached.
Generic interface
type ('a, 'b) t
The type of hash tables from type 'a to type 'b.
val add : ('a, 'b) t -> 'a -> 'b -> unit
Hashtbl.add tbl key data adds a binding of key to data in table tbl. Previous bindings
for key are not removed, but simply hidden. That is, after performing
Hashtbl.remove[25.22] tbl key, the previous binding for key, if any, is restored. (Same
behavior as with association lists.)
val replace : ('a, 'b) t -> 'a -> 'b -> unit
Hashtbl.replace tbl key data replaces the current binding of key in tbl by a binding of
key to data. If key is unbound in tbl, a binding of key to data is added to tbl. This is
functionally equivalent to Hashtbl.remove[25.22] tbl key followed by Hashtbl.add[25.22]
tbl key data.
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter f tbl applies f to all bindings in table tbl. f receives the key as first
argument, and the associated value as second argument. Each binding is presented exactly
once to f.
The order in which the bindings are passed to f is unspecified. However, if the table
contains several bindings for the same key, they are passed to f in reverse order of
introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are
enumerated is reproducible between successive runs of the program, and even between
minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely
random.
The behavior is not defined if the hash table is modified by f during the iteration.
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
Hashtbl.filter_map_inplace f tbl applies f to all bindings in table tbl and update
each binding depending on the result of f. If f returns None, the binding is discarded. If it
returns Some new_val, the binding is update to associate the key to new_val.
Other comments for Hashtbl.iter[25.22] apply as well.
Since: 4.03.0
val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
Hashtbl.fold f tbl init computes (f kN dN ... (f k1 d1 init)...), where k1 ...
kN are the keys of all bindings in tbl, and d1 ... dN are the associated values. Each
binding is presented exactly once to f.
The order in which the bindings are passed to f is unspecified. However, if the table
contains several bindings for the same key, they are passed to f in reverse order of
introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings are
enumerated is reproducible between successive runs of the program, and even between
minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely
random.
The behavior is not defined if the hash table is modified by f during the iteration.
Chapter 25. The standard library 611
type statistics =
{ num_bindings : int ;
Number of bindings present in the table. Same value as returned by
Hashtbl.length[25.22].
num_buckets : int ;
Number of buckets in the table.
max_bucket_length : int ;
Maximal number of bindings per bucket.
612
val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
Add the given bindings to the table, using Hashtbl.add[25.22]
Since: 4.07
val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
Add the given bindings to the table, using Hashtbl.replace[25.22]
Since: 4.07
Functorial interface
The functorial interface allows the use of specific comparison and hash functions, either for per-
formance/security concerns, or because keys are not hashable/comparable with the polymorphic
builtins.
For instance, one might want to specialize a table for integer keys:
module IntHash =
struct
type t = int
let equal i j = i=j
let hash i = i land max_int
end
let h = IntHashtbl.create 17 in
IntHashtbl.add h 12 "hello"
This creates a new module IntHashtbl, with a new type 'a IntHashtbl.t of tables from int
to 'a. In this example, h contains string values so its type is string IntHashtbl.t.
Note that the new type 'a IntHashtbl.t is not compatible with the type ('a,'b) Hashtbl.t
of the generic interface. For example, Hashtbl.length h would not type-check, you must use
IntHashtbl.length.
module type HashedType =
sig
type t
The type of the hashtable keys.
end
module type S =
sig
type key
type 'a t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
Since: 4.00.0
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val length : 'a t -> int
val stats : 'a t -> Hashtbl.statistics
Since: 4.00.0
Since: 4.07
end
module Make :
functor (H : HashedType) -> S with type key = H.t
Functor building an implementation of the hashtable structure. The functor Hashtbl.Make
returns a structure containing a type key of keys and a type 'a t of hash tables associating
data of type 'a to keys of type key. The operations perform similarly to those of the
generic interface, but use the hashing and equality functions specified in the functor
argument H instead of generic equality and hashing. Since the hash function is not seeded,
the create operation of the result structure always returns non-randomized hash tables.
end
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val length : 'a t -> int
val stats : 'a t -> Hashtbl.statistics
val to_seq : 'a t -> (key * 'a) Seq.t
Since: 4.07
end
The output signature of the functor Hashtbl.MakeSeeded[25.22].
Since: 4.00.0
module MakeSeeded :
functor (H : SeededHashedType) -> SeededS with type key = H.t
Functor building an implementation of the hashtable structure. The functor
Hashtbl.MakeSeeded returns a structure containing a type key of keys and a type 'a t of
hash tables associating data of type 'a to keys of type key. The operations perform
similarly to those of the generic interface, but use the seeded hashing and equality functions
specified in the functor argument H instead of generic equality and hashing. The create
operation of the result structure supports the ~random optional parameter and returns
randomized hash tables if ~random:true is passed or if randomization is globally on (see
Hashtbl.randomize[25.22]).
Since: 4.00.0
val seeded_hash_param : int -> int -> int -> 'a -> int
A variant of Hashtbl.hash_param[25.22] that is further parameterized by an integer seed.
Usage: Hashtbl.seeded_hash_param meaningful total seed x.
Since: 4.00.0
Integers
type t = int
The type for integer values.
Converting
val to_float : int -> float
to_float x is x as a floating point number.
type t = int32
An alias for the type of 32-bit integers.
624
type t = int64
An alias for the type of 64-bit integers.
let lazy_option_map f x =
match x with
| lazy (Some x) -> Some (Lazy.force f x)
Chapter 25. The standard library 629
| _ -> None
Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may
be forced even outside of the case ultimately selected by the pattern matching. In the
example above, the suspension x is always computed.
Note: lazy_t is the built-in type constructor used by the compiler for the lazy keyword.
You should not use it directly. Always use Lazy.t instead.
Note: Lazy.force is not thread-safe. If you use this module in a multi-threaded program,
you will need to add some locks.
Note: if the program is compiled with the -rectypes option, ill-founded recursive
definitions of the form let rec x = lazy x or let rec x = lazy(lazy(...(lazy x)))
are accepted by the type-checker and lead, when forced, to ill-formed values that trigger
infinite loops in the garbage collector and other parts of the run-time system. Without the
-rectypes option, such ill-founded recursive definitions are rejected by the type-checker.
exception Undefined
val force : 'a t -> 'a
force x forces the suspension x and returns its result. If x has already been forced,
Lazy.force x returns the same value again without recomputing it. If it raised an
exception, the same exception is raised again.
Raises Undefined if the forcing of x tries to force x itself recursively.
Iterators
val map : ('a -> 'b) -> 'a t -> 'b t
map f x returns a suspension that, when forced, forces x and applies f to its value.
It is equivalent to lazy (f (Lazy.force x)).
Since: 4.13.0
Advanced
The following definitions are for advanced uses only; they require familiary with the lazy compilation
scheme to be used appropriately.
val from_fun : (unit -> 'a) -> 'a t
from_fun f is the same as lazy (f ()) but slightly more efficient.
It should only be used if the function f is already defined. In particular it is always less
efficient to write from_fun (fun () -> expr) than lazy expr.
Since: 4.00.0
Deprecated
val lazy_from_fun : (unit -> 'a) -> 'a t
Deprecated. synonym for from_fun.
Positions
type position =
{ pos_fname : string ;
pos_lnum : int ;
pos_bol : int ;
pos_cnum : int ;
}
A value of type position describes a point in a source file. pos_fname is the file name;
pos_lnum is the line number; pos_bol is the offset of the beginning of the line (number of
characters between the beginning of the lexbuf and the beginning of the line); pos_cnum is
the offset of the position (number of characters between the beginning of the lexbuf and the
position). The difference between pos_cnum and pos_bol is the character offset within the
line (i.e. the column number, assuming each character is one column wide).
See the documentation of type lexbuf for information about how the lexing engine will
manage positions.
Lexer buffers
type lexbuf =
{ refill_buff : lexbuf -> unit ;
mutable lex_buffer : bytes ;
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_last_action : int ;
mutable lex_eof_reached : bool ;
mutable lex_mem : int array ;
mutable lex_start_p : position ;
mutable lex_curr_p : position ;
}
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.
632
Lexers can optionally maintain the lex_curr_p and lex_start_p position fields. This
"position tracking" mode is the default, and it corresponds to passing
~with_position:true to functions that create lexer buffers. In this mode, the lexing engine
and lexer actions are co-responsible for properly updating the position fields, as described in
the next paragraph. When the mode is explicitly disabled (with ~with_position:false),
the lexing engine will not touch the position fields and the lexer actions should be careful
not to do it either; the lex_curr_p and lex_start_p field will then always hold the
dummy_pos invalid position. Not tracking positions avoids allocations and memory writes
and can significantly improve the performance of the lexer in contexts where lex_start_p
and lex_curr_p are not needed.
Position tracking mode works as follows. At each token, the lexing engine will copy
lex_curr_p to lex_start_p, then change the pos_cnum field of lex_curr_p by updating it
with the number of characters read since the start of the lexbuf. The other fields are left
unchanged by the lexing engine. In order to keep them accurate, they must be initialised
before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end
of line – see also new_line).
val from_function : ?with_positions:bool -> (bytes -> 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 byte sequence s and a byte
count n. The function should put n bytes or fewer in s, starting at index 0, and return the
number of bytes provided. A return value of 0 means end of input.
Tell whether the lexer buffer keeps track of position fields lex_curr_p / lex_start_p, as
determined by the corresponding optional argument for functions that create lexer buffers
(whose default value is true).
When with_positions is false, lexer actions should not modify position fields. Doing it
nevertheless could re-enable the with_position mode and degrade performances.
Miscellaneous functions
val flush_input : lexbuf -> unit
Discard the contents of the buffer and reset the current position to 0. The next use of the
lexbuf will trigger a refill.
val init : int -> (int -> 'a) -> 'a list
init len f is f 0; f 1; ...; f (len-1), evaluated left to right.
Since: 4.06.0
Raises Invalid_argument if len < 0.
val append : 'a list -> 'a list -> 'a list
Concatenate two lists. Same function as the infix operator @. Not tail-recursive (length of
the first argument). The @ operator is not tail-recursive either.
val rev_append : 'a list -> 'a list -> 'a list
rev_append l1 l2 reverses l1 and concatenates it with l2. This is equivalent to
(List.rev[25.28] l1) @ l2, but rev_append is tail-recursive and more efficient.
Comparison
val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool
equal eq [a1; ...; an] [b1; ..; bm] holds when the two input lists have the same
length, and for each pair of elements ai, bi at the same position we have eq ai bi.
Note: the eq function may be called even if the lists have different length. If you know your
equality function is costly, you may want to check List.compare_lengths[25.28] first.
Since: 4.12.0
val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int
compare cmp [a1; ...; an] [b1; ...; bm] performs a lexicographic comparison of the
two input lists, using the same 'a -> 'a -> int interface as compare[24.2]:
Note: the cmp function will be called even if the lists have different lengths.
Since: 4.12.0
Iterators
val iter : ('a -> unit) -> 'a list -> unit
iter f [a1; ...; an] applies function f in turn to a1; ...; an. It is equivalent to
begin f a1; f a2; ...; f an; () end.
val iteri : (int -> 'a -> unit) -> 'a list -> unit
Same as List.iter[25.28], but the function is applied to the index of the element as first
argument (counting from 0), and the element itself as second argument.
Since: 4.00.0
val map : ('a -> 'b) -> 'a list -> 'b 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. Not tail-recursive.
val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list
Same as List.map[25.28], but the function is applied to the index of the element as first
argument (counting from 0), and the element itself as second argument. Not tail-recursive.
Since: 4.00.0
val rev_map : ('a -> 'b) -> 'a list -> 'b list
rev_map f l gives the same result as List.rev[25.28] (List.map[25.28] f l), but is
tail-recursive and more efficient.
Chapter 25. The standard library 637
val filter_map : ('a -> 'b option) -> 'a list -> 'b list
filter_map f l applies f to every element of l, filters out the None elements and returns
the list of the arguments of the Some elements.
Since: 4.08.0
val concat_map : ('a -> 'b list) -> 'a list -> 'b list
concat_map f l gives the same result as List.concat[25.28] (List.map[25.28] f l).
Tail-recursive.
Since: 4.10.0
val fold_left_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b list -> 'a * 'c list
fold_left_map is a combination of fold_left and map that threads an accumulator
through calls to f.
Since: 4.11.0
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
fold_left f init [b1; ...; bn] is f (... (f (f init b1) b2) ...) bn.
val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
fold_right f [a1; ...; an] init is f a1 (f a2 (... (f an init) ...)). Not
tail-recursive.
val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
map2 f [a1; ...; an] [b1; ...; bn] is [f a1 b1; ...; f an bn].
Raises Invalid_argument if the two lists are determined to have different lengths. Not
tail-recursive.
val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
rev_map2 f l1 l2 gives the same result as List.rev[25.28] (List.map2[25.28] f l1 l2),
but is tail-recursive and more efficient.
val fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b list -> 'c list -> 'a
fold_left2 f init [a1; ...; an] [b1; ...; bn] is f (... (f (f init a1 b1) a2
b2) ...) an bn.
Raises Invalid_argument if the two lists are determined to have different lengths.
638
val fold_right2 : ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
fold_right2 f [a1; ...; an] [b1; ...; bn] init is f a1 b1 (f a2 b2 (... (f an
bn init) ...)).
Raises Invalid_argument if the two lists are determined to have different lengths. Not
tail-recursive.
List scanning
val for_all : ('a -> bool) -> 'a list -> bool
for_all f [a1; ...; an] checks if all elements of the list satisfy the predicate f. That is,
it returns (f a1) && (f a2) && ... && (f an) for a non-empty list and true if the list
is empty.
val exists : ('a -> bool) -> 'a list -> bool
exists f [a1; ...; an] checks if at least one element of the list satisfies the predicate f.
That is, it returns (f a1) || (f a2) || ... || (f an) for a non-empty list and false
if the list is empty.
val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as List.for_all[25.28], but for a two-argument predicate.
Raises Invalid_argument if the two lists are determined to have different lengths.
val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as List.exists[25.28], but for a two-argument predicate.
Raises Invalid_argument if the two lists are determined to have different lengths.
List searching
val find : ('a -> bool) -> 'a list -> 'a
find f l returns the first element of the list l that satisfies the predicate f.
Raises Not_found if there is no value that satisfies f in the list l.
val find_opt : ('a -> bool) -> 'a list -> 'a option
Chapter 25. The standard library 639
find f l returns the first element of the list l that satisfies the predicate f. Returns None
if there is no value that satisfies f in the list l.
Since: 4.05
val find_map : ('a -> 'b option) -> 'a list -> 'b option
find_map f l applies f to the elements of l in order, and returns the first result of the
form Some v, or None if none exist.
Since: 4.10.0
val filter : ('a -> bool) -> 'a list -> 'a list
filter f l returns all the elements of the list l that satisfy the predicate f. The order of
the elements in the input list is preserved.
val find_all : ('a -> bool) -> 'a list -> 'a list
find_all is another name for List.filter[25.28].
val filteri : (int -> 'a -> bool) -> 'a list -> 'a list
Same as List.filter[25.28], but the predicate is applied to the index of the element as first
argument (counting from 0), and the element itself as second argument.
Since: 4.11.0
val partition : ('a -> bool) -> 'a list -> 'a list * 'a list
partition f l returns a pair of lists (l1, l2), where l1 is the list of all the elements of l
that satisfy the predicate f, and l2 is the list of all the elements of l that do not satisfy f.
The order of the elements in the input list is preserved.
val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
partition_map f l returns a pair of lists (l1, l2) such that, for each element x of the
input list l:
The output elements are included in l1 and l2 in the same relative order as the
corresponding input elements in l.
In particular, partition_map (fun x -> if f x then Left x else Right x) l is
equivalent to partition f l.
Since: 4.12.0
640
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.
Raises Not_found if there is no value associated with a in the list l.
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
assoc_opt a l returns the value associated with key a in the list of pairs l. That is,
assoc_opt a [ ...; (a,b); ...] = Some b if (a,b) is the leftmost binding of a in list
l. Returns None if there is no value associated with a in the list l.
Since: 4.05
val assq_opt : 'a -> ('a * 'b) list -> 'b option
Same as List.assoc_opt[25.28], but uses physical equality instead of structural equality to
compare keys.
Since: 4.05.0
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
remove_assoc a l returns the list of pairs l without the first pair with key a, if any. Not
tail-recursive.
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
Same as List.remove_assoc[25.28], but uses physical equality instead of structural equality
to compare keys. Not tail-recursive.
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]). Not tail-recursive.
Chapter 25. The standard library 641
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)].
Raises Invalid_argument if the two lists have different lengths. Not tail-recursive.
Sorting
val sort : ('a -> 'a -> int) -> 'a list -> 'a list
Sort a list in increasing order according to a comparison function. The comparison function
must return 0 if its arguments compare as equal, a positive integer if the first is greater, and
a negative integer if the first is smaller (see Array.sort for a complete specification). For
example, compare[24.2] is a suitable comparison function. The resulting list is sorted in
increasing order. List.sort[25.28] is guaranteed to run in constant heap space (in addition
to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and
logarithmic stack space.
val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list
Same as List.sort[25.28], but the sorting algorithm is guaranteed to be stable (i.e.
elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and
logarithmic stack space.
val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list
Same as List.sort[25.28] or List.stable_sort[25.28], whichever is faster on typical input.
val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list
Same as List.sort[25.28], but also remove duplicates.
Since: 4.02.0 (4.03.0 in ListLabels)
val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
Merge two lists: Assuming that l1 and l2 are sorted according to the comparison function
cmp, merge cmp l1 l2 will return a sorted list containing all the elements of l1 and l2. If
several elements compare equal, the elements of l1 will be before the elements of l2. Not
tail-recursive (sum of the lengths of the arguments).
val init : len:int -> f:(int -> 'a) -> 'a list
init ~len ~f is f 0; f 1; ...; f (len-1), evaluated left to right.
Since: 4.06.0
Raises Invalid_argument if len < 0.
val append : 'a list -> 'a list -> 'a list
Concatenate two lists. Same function as the infix operator @. Not tail-recursive (length of
the first argument). The @ operator is not tail-recursive either.
val rev_append : 'a list -> 'a list -> 'a list
rev_append l1 l2 reverses l1 and concatenates it with l2. This is equivalent to
(ListLabels.rev[25.29] l1) @ l2, but rev_append is tail-recursive and more efficient.
Comparison
val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool
equal eq [a1; ...; an] [b1; ..; bm] holds when the two input lists have the same
length, and for each pair of elements ai, bi at the same position we have eq ai bi.
Note: the eq function may be called even if the lists have different length. If you know your
equality function is costly, you may want to check ListLabels.compare_lengths[25.29]
first.
Since: 4.12.0
val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int
compare cmp [a1; ...; an] [b1; ...; bm] performs a lexicographic comparison of the
two input lists, using the same 'a -> 'a -> int interface as compare[24.2]:
Note: the cmp function will be called even if the lists have different lengths.
Since: 4.12.0
Iterators
val iter : f:('a -> unit) -> 'a list -> unit
iter ~f [a1; ...; an] applies function f in turn to a1; ...; an. It is equivalent to
begin f a1; f a2; ...; f an; () end.
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
Same as ListLabels.iter[25.29], but the function is applied to the index of the element as
first argument (counting from 0), and the element itself as second argument.
Since: 4.00.0
val map : f:('a -> 'b) -> 'a list -> 'b 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. Not tail-recursive.
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
Same as ListLabels.map[25.29], but the function is applied to the index of the element as
first argument (counting from 0), and the element itself as second argument. Not
tail-recursive.
Since: 4.00.0
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
Chapter 25. The standard library 645
val filter_map : f:('a -> 'b option) -> 'a list -> 'b list
filter_map ~f l applies f to every element of l, filters out the None elements and returns
the list of the arguments of the Some elements.
Since: 4.08.0
val concat_map : f:('a -> 'b list) -> 'a list -> 'b list
concat_map ~f l gives the same result as ListLabels.concat[25.29]
(ListLabels.map[25.29] f l). Tail-recursive.
Since: 4.10.0
val fold_left_map :
f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b list -> 'a * 'c list
fold_left_map is a combination of fold_left and map that threads an accumulator
through calls to f.
Since: 4.11.0
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
fold_left ~f ~init [b1; ...; bn] is f (... (f (f init b1) b2) ...) bn.
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
fold_right ~f [a1; ...; an] ~init is f a1 (f a2 (... (f an init) ...)). Not
tail-recursive.
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
map2 ~f [a1; ...; an] [b1; ...; bn] is [f a1 b1; ...; f an bn].
Raises Invalid_argument if the two lists are determined to have different lengths. Not
tail-recursive.
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
rev_map2 ~f l1 l2 gives the same result as ListLabels.rev[25.29]
(ListLabels.map2[25.29] f l1 l2), but is tail-recursive and more efficient.
val fold_left2 :
f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
646
fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn] is f (... (f (f init a1 b1)
a2 b2) ...) an bn.
Raises Invalid_argument if the two lists are determined to have different lengths.
val fold_right2 :
f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init is f a1 b1 (f a2 b2 (... (f
an bn init) ...)).
Raises Invalid_argument if the two lists are determined to have different lengths. Not
tail-recursive.
List scanning
val for_all : f:('a -> bool) -> 'a list -> bool
for_all ~f [a1; ...; an] checks if all elements of the list satisfy the predicate f. That
is, it returns (f a1) && (f a2) && ... && (f an) for a non-empty list and true if the
list is empty.
val exists : f:('a -> bool) -> 'a list -> bool
exists ~f [a1; ...; an] checks if at least one element of the list satisfies the predicate f.
That is, it returns (f a1) || (f a2) || ... || (f an) for a non-empty list and false
if the list is empty.
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as ListLabels.for_all[25.29], but for a two-argument predicate.
Raises Invalid_argument if the two lists are determined to have different lengths.
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as ListLabels.exists[25.29], but for a two-argument predicate.
Raises Invalid_argument if the two lists are determined to have different lengths.
List searching
val find : f:('a -> bool) -> 'a list -> 'a
find ~f l returns the first element of the list l that satisfies the predicate f.
Raises Not_found if there is no value that satisfies f in the list l.
val find_opt : f:('a -> bool) -> 'a list -> 'a option
find ~f l returns the first element of the list l that satisfies the predicate f. Returns None
if there is no value that satisfies f in the list l.
Since: 4.05
val find_map : f:('a -> 'b option) -> 'a list -> 'b option
find_map ~f l applies f to the elements of l in order, and returns the first result of the
form Some v, or None if none exist.
Since: 4.10.0
val filter : f:('a -> bool) -> 'a list -> 'a list
filter ~f l returns all the elements of the list l that satisfy the predicate f. The order of
the elements in the input list is preserved.
val find_all : f:('a -> bool) -> 'a list -> 'a list
find_all is another name for ListLabels.filter[25.29].
val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list
Same as ListLabels.filter[25.29], but the predicate is applied to the index of the element
as first argument (counting from 0), and the element itself as second argument.
Since: 4.11.0
val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
partition ~f l returns a pair of lists (l1, l2), where l1 is the list of all the elements of
l that satisfy the predicate f, and l2 is the list of all the elements of l that do not satisfy f.
The order of the elements in the input list is preserved.
val partition_map :
f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
partition_map f l returns a pair of lists (l1, l2) such that, for each element x of the
input list l:
• if f x is Left y1, then y1 is in l1, and
• if f x is Right y2, then y2 is in l2.
The output elements are included in l1 and l2 in the same relative order as the
corresponding input elements in l.
In particular, partition_map (fun x -> if f x then Left x else Right x) l is
equivalent to partition f l.
Since: 4.12.0
648
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.
Raises Not_found if there is no value associated with a in the list l.
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
assoc_opt a l returns the value associated with key a in the list of pairs l. That is,
assoc_opt a [ ...; (a,b); ...] = Some b if (a,b) is the leftmost binding of a in list
l. Returns None if there is no value associated with a in the list l.
Since: 4.05
val assq_opt : 'a -> ('a * 'b) list -> 'b option
Same as ListLabels.assoc_opt[25.29], but uses physical equality instead of structural
equality to compare keys.
Since: 4.05.0
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
remove_assoc a l returns the list of pairs l without the first pair with key a, if any. Not
tail-recursive.
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
Same as ListLabels.remove_assoc[25.29], but uses physical equality instead of structural
equality to compare keys. Not tail-recursive.
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]). Not tail-recursive.
Chapter 25. The standard library 649
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)].
Raises Invalid_argument if the two lists have different lengths. Not tail-recursive.
Sorting
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
Sort a list in increasing order according to a comparison function. The comparison function
must return 0 if its arguments compare as equal, a positive integer if the first is greater, and
a negative integer if the first is smaller (see Array.sort for a complete specification). For
example, compare[24.2] is a suitable comparison function. The resulting list is sorted in
increasing order. ListLabels.sort[25.29] is guaranteed to run in constant heap space (in
addition to the size of the result list) and logarithmic stack space.
The current implementation uses Merge Sort. It runs in constant heap space and
logarithmic stack space.
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
Same as ListLabels.sort[25.29], but the sorting algorithm is guaranteed to be stable (i.e.
elements that compare equal are kept in their original order).
The current implementation uses Merge Sort. It runs in constant heap space and
logarithmic stack space.
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
Same as ListLabels.sort[25.29] or ListLabels.stable_sort[25.29], whichever is faster
on typical input.
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
Same as ListLabels.sort[25.29], but also remove duplicates.
Since: 4.03.0
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
Merge two lists: Assuming that l1 and l2 are sorted according to the comparison function
cmp, merge ~cmp l1 l2 will return a sorted list containing all the elements of l1 and l2. If
several elements compare equal, the elements of l1 will be before the elements of l2. Not
tail-recursive (sum of the lengths of the arguments).
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
This creates a new module PairsMap, with a new type 'a PairsMap.t of maps from int *
int to 'a. In this example, m contains string values so its type is string PairsMap.t.
end
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 update : key -> ('a option -> 'a option) -> 'a t -> 'a t
update key f m returns a map containing the same bindings as m, except for the
binding of key. Depending on the value of y where y is f (find_opt key m), the
binding of key is added, removed or updated. If y is None, the binding is removed if it
exists; otherwise, if y is Some z then key is associated to z in the resulting map. If key
was already bound in m to a value that is physically equal to z, m is returned
unchanged (the result of the function is then physically equal to m).
Since: 4.06.0
val merge :
(key -> 'a option -> 'b option -> 'c option) ->
'a t -> 'b t -> 'c t
merge f m1 m2 computes a map whose keys are a subset of the keys of m1 and of m2.
The presence of each such binding, and the corresponding value, is determined with
the function f. In terms of the find_opt operation, we have find_opt x (merge f
m1 m2) = f x (find_opt x m1) (find_opt x m2) for any key x, provided that f x
None None = None.
Since: 3.12.0
val union : (key -> 'a -> 'a -> 'a option) ->
'a t -> 'a t -> 'a t
union f m1 m2 computes a map whose keys are a subset of the keys of m1 and of m2.
When the same binding is defined in both arguments, the function f is used to combine
them. This is a special case of merge: union f m1 m2 is equivalent to merge f' m1
m2, where
• f' _key None None = None
• f' _key (Some v) None = Some v
• f' _key None (Some v) = Some v
• f' key (Some v1) (Some v2) = f key v1 v2
Since: 4.03.0
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
Total ordering between maps. The first argument is a total ordering used to compare
data associated with equal keys in the two maps.
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
equal cmp m1 m2 tests whether the maps m1 and m2 are equal, that is, contain equal
keys and associate them with equal data. cmp is the equality predicate used to compare
the data associated with the keys.
val iter : (key -> 'a -> unit) -> 'a t -> unit
iter f m applies f to all bindings in map m. f receives the key as first argument, and
the associated value as second argument. The bindings are passed to f in increasing
order with respect to the ordering over the type of the keys.
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
fold f m init computes (f kN dN ... (f k1 d1 init)...), where k1 ... kN
are the keys of all bindings in m (in increasing order), and d1 ... dN are the
associated data.
val for_all : (key -> 'a -> bool) -> 'a t -> bool
Chapter 25. The standard library 653
for_all f m checks if all the bindings of the map satisfy the predicate f.
Since: 3.12.0
val exists : (key -> 'a -> bool) -> 'a t -> bool
exists f m checks if at least one binding of the map satisfies the predicate f.
Since: 3.12.0
val filter : (key -> 'a -> bool) -> 'a t -> 'a t
filter f m returns the map with all the bindings in m that satisfy predicate p. If
every binding in m satisfies f, m is returned unchanged (the result of the function is
then physically equal to m)
Before 4.03 Physical equality was not ensured.
Since: 3.12.0
val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t
filter_map f m applies the function f to every binding of m, and builds a map from
the results. For each binding (k, v) in the input map:
• if f k v is None then k is not in the result,
• if f k v is Some v' then the binding (k, v') is in the output map.
For example, the following function on maps whose values are lists
filter_map
(fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
drops all bindings of m whose value is an empty list, and pops the first element of each
value that is non-empty.
Since: 4.11.0
val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
partition f m returns a pair of maps (m1, m2), where m1 contains all the bindings of
m that satisfy the predicate f, and m2 is the map with all the bindings of m that do not
satisfy f.
Since: 3.12.0
Return the list of all bindings of the given map. The returned list is sorted in
increasing order of keys with respect to the ordering Ord.compare, where Ord is the
argument given to Map.Make[25.30].
Since: 3.12.0
val split : key -> 'a t -> 'a t * 'a option * 'a t
split x m returns a triple (l, data, r), where l is the map with all the bindings of
m whose key is strictly less than x; r is the map with all the bindings of m whose key is
strictly greater than x; data is None if m contains no binding for x, or Some v if m binds
v to x.
Since: 3.12.0
Chapter 25. The standard library 655
val find_first : (key -> bool) -> 'a t -> key * 'a
find_first f m, where f is a monotonically increasing function, returns the binding
of m with the lowest key k such that f k, or raises Not_found if no such key exists.
For example, find_first (fun k -> Ord.compare k x >= 0) m will return the first
binding k, v of m where Ord.compare k x >= 0 (intuitively: k >= x), or raise
Not_found if x is greater than any element of m.
Since: 4.05
val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option
find_first_opt f m, where f is a monotonically increasing function, returns an
option containing the binding of m with the lowest key k such that f k, or None if no
such key exists.
Since: 4.05
val find_last : (key -> bool) -> 'a t -> key * 'a
find_last f m, where f is a monotonically decreasing function, returns the binding of
m with the highest key k such that f k, or raises Not_found if no such key exists.
Since: 4.05
val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option
find_last_opt f m, where f is a monotonically decreasing function, returns an option
containing the binding of m with the highest key k such that f k, or None if no such
key exists.
Since: 4.05
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
Same as Map.S.map[25.30], but the function receives as arguments both the key and
the associated value for each binding of the map.
656
end
Output signature of the functor Map.Make[25.30].
module Make :
functor (Ord : OrderedType) -> S with type key = Ord.t
Functor building an implementation of the map structure given a totally ordered type.
Values of extensible variant types, for example exceptions (of extensible type exn), returned
by the unmarshaller should not be pattern-matched over through match ... with or try ...
with, because unmarshalling does not preserve the information required for matching their con-
structors. Structural equalities with other extensible variant values does not work either. Most
other uses such as Printexc.to_string, will still work as expected.
The representation of marshaled values is not human-readable, and uses bytes that are not
printable characters. Therefore, input and output channels used in conjunction with Marshal.to_
channel and Marshal.from_channel must be opened in binary mode, using e.g. open_out_bin
or open_in_bin; channels opened in text mode will cause unmarshaling errors on platforms where
text channels behave differently than binary channels, e.g. Windows.
type extern_flags =
| No_sharing
Don’t preserve sharing
| Closures
Send function closures
| Compat_32
Ensure 32-bit compatibility
The flags to the Marshal.to_* functions below.
val to_channel : out_channel -> 'a -> extern_flags list -> unit
Marshal.to_channel chan v flags writes the representation of v on channel chan. The
flags argument is a possibly empty list of flags that governs the marshaling behavior with
respect to sharing, functional values, and compatibility between 32- and 64-bit platforms.
If flags does not contain Marshal.No_sharing, circularities and sharing inside the value v
are detected and preserved in the sequence of bytes produced. In particular, this guarantees
that marshaling always terminates. Sharing between values marshaled by successive calls to
Marshal.to_channel is neither detected nor preserved, though. If flags contains
Marshal.No_sharing, sharing is ignored. This results in faster marshaling if v contains no
shared substructures, but may cause slower marshaling and larger byte representations if v
actually contains sharing, or even non-termination if v contains cycles.
If flags does not contain Marshal.Closures, marshaling fails when it encounters a
functional value inside v: only ’pure’ data structures, containing neither functions nor
objects, can safely be transmitted between different programs. If flags contains
Marshal.Closures, functional values will be marshaled as a the position in the code of the
program together with the values corresponding to the free variables captured in the closure.
In this case, the output of marshaling can only be read back in processes that run exactly
the same program, with exactly the same compiled code. (This is checked at un-marshaling
time, using an MD5 digest of the code transmitted along with the code position.)
658
The exact definition of which free variables are captured in a closure is not specified and can
vary between bytecode and native code (and according to optimization flags). In particular,
a function value accessing a global reference may or may not include the reference in its
closure. If it does, unmarshaling the corresponding closure will create a new reference,
different from the global one.
If flags contains Marshal.Compat_32, marshaling fails when it encounters an integer value
outside the range [-2{^30}, 2{^30}-1] of integers that are representable on a 32-bit
platform. This ensures that marshaled data generated on a 64-bit platform can be safely
read back on a 32-bit platform. If flags does not contain Marshal.Compat_32, integer
values outside the range [-2{^30}, 2{^30}-1] are marshaled, and can be read back on a
64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit
platform. The Mashal.Compat_32 flag only matters when marshaling is performed on a
64-bit platform; it has no effect if marshaling is performed on a 32-bit platform.
Raises Failure if chan is not in binary mode.
val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int
Marshal.to_buffer buff ofs len v flags marshals the value v, storing its byte
representation in the sequence buff, starting at index ofs, and writing at most len bytes.
It returns the number of bytes actually written to the sequence. If the byte representation
of v does not fit in len characters, the exception Failure is raised.
Since: 4.02.0
open MoreLabels
module Hashtbl :
sig
Hash tables and hash functions.
Hash tables are hashed association tables, with in-place modification.
660
Generic interface
type ('a, 'b) t = ('a, 'b) Hashtbl.t
The type of hash tables from type 'a to type 'b.
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
Hashtbl.add tbl ~key ~data adds a binding of key to data in table tbl. Previous
bindings for key are not removed, but simply hidden. That is, after performing
MoreLabels.Hashtbl.remove[25.32] tbl key, the previous binding for key, if any, is
restored. (Same behavior as with association lists.)
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
Hashtbl.replace tbl ~key ~data replaces the current binding of key in tbl by a
binding of key to data. If key is unbound in tbl, a binding of key to data is added to
tbl. This is functionally equivalent to MoreLabels.Hashtbl.remove[25.32] tbl key
followed by MoreLabels.Hashtbl.add[25.32] tbl key data.
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
Hashtbl.iter ~f tbl applies f to all bindings in table tbl. f receives the key as first
argument, and the associated value as second argument. Each binding is presented
exactly once to f.
The order in which the bindings are passed to f is unspecified. However, if the table
contains several bindings for the same key, they are passed to f in reverse order of
introduction, that is, the most recent binding is passed first.
662
If the hash table was created in non-randomized mode, the order in which the bindings
are enumerated is reproducible between successive runs of the program, and even
between minor versions of OCaml. For randomized hash tables, the order of
enumeration is entirely random.
The behavior is not defined if the hash table is modified by f during the iteration.
val filter_map_inplace :
f:(key:'a -> data:'b -> 'b option) -> ('a, 'b) t -> unit
Hashtbl.filter_map_inplace ~f tbl applies f to all bindings in table tbl and
update each binding depending on the result of f. If f returns None, the binding is
discarded. If it returns Some new_val, the binding is update to associate the key to
new_val.
Other comments for MoreLabels.Hashtbl.iter[25.32] apply as well.
Since: 4.03.0
val fold : f:(key:'a -> data:'b -> 'c -> 'c) ->
('a, 'b) t -> init:'c -> 'c
Hashtbl.fold ~f tbl ~init computes (f kN dN ... (f k1 d1 init)...), where
k1 ... kN are the keys of all bindings in tbl, and d1 ... dN are the associated
values. Each binding is presented exactly once to f.
The order in which the bindings are passed to f is unspecified. However, if the table
contains several bindings for the same key, they are passed to f in reverse order of
introduction, that is, the most recent binding is passed first.
If the hash table was created in non-randomized mode, the order in which the bindings
are enumerated is reproducible between successive runs of the program, and even
between minor versions of OCaml. For randomized hash tables, the order of
enumeration is entirely random.
The behavior is not defined if the hash table is modified by f during the iteration.
Note that once Hashtbl.randomize() was called, there is no way to revert to the
non-randomized default behavior of MoreLabels.Hashtbl.create[25.32]. This is
intentional. Non-randomized hash tables can still be created using Hashtbl.create
~random:false.
Since: 4.00.0
Hashtbl.stats tbl returns statistics about the table tbl: number of buckets, size of
the biggest bucket, distribution of buckets by size.
Since: 4.00.0
val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
Add the given bindings to the table, using MoreLabels.Hashtbl.add[25.32]
Since: 4.07
val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
Add the given bindings to the table, using MoreLabels.Hashtbl.replace[25.32]
Since: 4.07
Functorial interface
The functorial interface allows the use of specific comparison and hash functions, either for
performance/security concerns, or because keys are not hashable/comparable with the poly-
morphic builtins.
For instance, one might want to specialize a table for integer keys:
module IntHash =
struct
type t = int
let equal i j = i=j
let hash i = i land max_int
end
let h = IntHashtbl.create 17 in
IntHashtbl.add h 12 "hello"
This creates a new module IntHashtbl, with a new type 'a IntHashtbl.t of tables from
int to 'a. In this example, h contains string values so its type is string IntHashtbl.t.
Note that the new type 'a IntHashtbl.t is not compatible with the type ('a,'b)
Hashtbl.t of the generic interface. For example, Hashtbl.length h would not type-check,
you must use IntHashtbl.length.
module type HashedType =
sig
type t
The type of the hashtable keys.
end
module type S =
sig
type key
type 'a t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
Since: 4.00.0
val fold : f:(key:key -> data:'a -> 'b -> 'b) ->
'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> MoreLabels.Hashtbl.statistics
Since: 4.00.0
end
module Make :
functor (H : HashedType) -> S with type key = H.t and type 'a t = 'a
Hashtbl.Make(H).t
Functor building an implementation of the hashtable structure. The functor
Hashtbl.Make returns a structure containing a type key of keys and a type 'a t of
hash tables associating data of type 'a to keys of type key. The operations perform
similarly to those of the generic interface, but use the hashing and equality functions
specified in the functor argument H instead of generic equality and hashing. Since the
hash function is not seeded, the create operation of the result structure always returns
non-randomized hash tables.
type t
The type of the hashtable keys.
end
type key
type 'a t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t ->
key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t ->
key -> 'a option
Since: 4.05.0
val fold : f:(key:key -> data:'a -> 'b -> 'b) ->
'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> MoreLabels.Hashtbl.statistics
val to_seq : 'a t ->
(key * 'a) Seq.t
Since: 4.07
Since: 4.07
end
module MakeSeeded :
functor (H : SeededHashedType) -> SeededS with type key = H.t and type 'a t
= 'a Hashtbl.MakeSeeded(H).t
Functor building an implementation of the hashtable structure. The functor
Hashtbl.MakeSeeded returns a structure containing a type key of keys and a type 'a
t of hash tables associating data of type 'a to keys of type key. The operations
perform similarly to those of the generic interface, but use the seeded hashing and
equality functions specified in the functor argument H instead of generic equality and
hashing. The create operation of the result structure supports the ~random optional
parameter and returns randomized hash tables if ~random:true is passed or if
randomization is globally on (see MoreLabels.Hashtbl.randomize[25.32]).
Since: 4.00.0
val seeded_hash_param : int -> int -> int -> 'a -> int
A variant of MoreLabels.Hashtbl.hash_param[25.32] that is further parameterized by
an integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x.
Since: 4.00.0
end
module Map :
sig
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
Chapter 25. The standard library 671
let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
This creates a new module PairsMap, with a new type 'a PairsMap.t of maps from int *
int to 'a. In this example, m contains string values so its type is string PairsMap.t.
module type OrderedType =
sig
type t
The type of the map keys.
end
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.
add ~key ~data m returns a map containing the same bindings as m, plus a
binding of key to data. If key was already bound in m to a value that is physically
equal to data, m is returned unchanged (the result of the function is then
physically equal to m). Otherwise, the previous binding of key in m disappears.
Before 4.03 Physical equality was not ensured.
val merge :
f:(key -> 'a option -> 'b option -> 'c option) ->
'a t -> 'b t -> 'c t
merge ~f m1 m2 computes a map whose keys are a subset of the keys of m1 and of
m2. The presence of each such binding, and the corresponding value, is determined
with the function f. In terms of the find_opt operation, we have find_opt x
(merge f m1 m2) = f x (find_opt x m1) (find_opt x m2) for any key x,
provided that f x None None = None.
Since: 3.12.0
val union : f:(key -> 'a -> 'a -> 'a option) ->
'a t -> 'a t -> 'a t
union ~f m1 m2 computes a map whose keys are a subset of the keys of m1 and of
m2. When the same binding is defined in both arguments, the function f is used to
combine them. This is a special case of merge: union f m1 m2 is equivalent to
merge f' m1 m2, where
• f' _key None None = None
• f' _key (Some v) None = Some v
• f' _key None (Some v) = Some v
Chapter 25. The standard library 673
val fold : f:(key:key -> data:'a -> 'b -> 'b) ->
'a t -> init:'b -> 'b
fold ~f m ~init computes (f kN dN ... (f k1 d1 init)...), where k1 ...
kN are the keys of all bindings in m (in increasing order), and d1 ... dN are the
associated data.
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
for_all ~f m checks if all the bindings of the map satisfy the predicate f.
Since: 3.12.0
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
exists ~f m checks if at least one binding of the map satisfies the predicate f.
Since: 3.12.0
filter_map
(fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
drops all bindings of m whose value is an empty list, and pops the first element of
each value that is non-empty.
Since: 4.11.0
end
module Make :
functor (Ord : OrderedType) -> S with type key = Ord.t and type 'a t = 'a
Map.Make(Ord).t
Functor building an implementation of the map structure given a totally ordered type.
end
module Set :
sig
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
678
This creates a new module PairsSet, with a new type PairsSet.t of sets of int * int.
module type OrderedType =
sig
type t
The type of the set elements.
end
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 fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
fold ~f s init computes (f xN ... (f x2 (f x1 init))...), where x1 ...
xN are the elements of s, in increasing order.
Iterators
val to_seq_from : elt ->
t -> elt Seq.t
to_seq_from x s iterates on a subset of the elements of s in ascending order,
from x or above.
Since: 4.07
end
module Make :
functor (Ord : OrderedType) -> S with type elt = Ord.t and type t =
Set.Make(Ord).t
Functor building an implementation of the set structure given a totally ordered type.
end
Subtraction.
The smallest representable native integer, either -231 on a 32-bit platform, or -263 on a
64-bit platform.
type t = nativeint
An alias for the type of native integers.
Options
type 'a t = 'a option =
| None
| Some of 'a
The type for option values. Either None or a value Some v.
some v is Some v.
val bind : 'a option -> ('a -> 'b option) -> 'b option
bind o f is f v if o is Some v and None if o is None.
val map : ('a -> 'b) -> 'a option -> 'b option
map f o is None if o is None and Some (f v) is o is Some v.
val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a
fold ~none ~some o is none if o is None and some v if o is Some v.
val iter : ('a -> unit) -> 'a option -> unit
iter f o is f v if o is Some v and () otherwise.
val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool
equal eq o0 o1 is true if and only if o0 and o1 are both None or if they are Some v0 and
Some v1 and eq v0 v1 is true.
val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int
compare cmp o0 o1 is a total order on options using cmp to compare values wrapped by
Some _. None is smaller than Some _ values.
Chapter 25. The standard library 689
Converting
val to_result : none:'e -> 'a option -> ('a, 'e) result
to_result ~none o is Ok v if o is Some v and Error none otherwise.
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.
type t = exn = ..
The type of exception values.
When using this mechanism, one should be aware that an exception backtrace is attached to
the thread that saw it raised, rather than to the exception itself. Practically, it means that
the code related to fn should not use the backtrace if it has itself raised an exception before.
Since: 3.11.2
Raw backtraces
type raw_backtrace
The type raw_backtrace stores a backtrace in a low-level format, which can be converted
to usable form using raw_backtrace_entries and backtrace_slots_of_raw_entry below.
Converting backtraces to backtrace_slots is slower than capturing the backtraces. If an
application processes many backtraces, it can be useful to use raw_backtrace to avoid or
delay conversion.
Raw backtraces cannot be marshalled. If you need marshalling, you should use the array
returned by the backtrace_slots function of the next section.
Since: 4.01.0
Uncaught exceptions
val default_uncaught_exception_handler : exn -> raw_backtrace -> unit
Printexc.default_uncaught_exception_handler prints the exception and backtrace on
standard error output.
Since: 4.11
If fn raises an exception, both the exceptions passed to fn and raised by fn will be printed
with their respective backtrace.
Since: 4.02.0
• none of the slots in the trace come from modules compiled with debug information (-g)
• the program is a bytecode program that has not been linked with debug information
enabled (ocamlc -g)
Since: 4.02.0
val backtrace_slots_of_raw_entry :
raw_backtrace_entry -> backtrace_slot array option
Returns the slots of a single raw backtrace entry, or None if this entry lacks debug
information.
Slots are returned in the same order as backtrace_slots: the slot at index 0 is the most
recent call, raise, or primitive, and subsequent slots represent callers.
Since: 4.12
type location =
{ filename : string ;
line_number : int ;
start_char : int ;
end_char : int ;
}
The type of location information found in backtraces. start_char and end_char are
positions relative to the beginning of the line.
Since: 4.02
Chapter 25. The standard library 695
module Slot :
sig
type t = Printexc.backtrace_slot
val is_raise : t -> bool
is_raise slot is true when slot refers to a raising point in the code, and false
when it comes from a simple function call.
Since: 4.02
end
Since: 4.02.0
696
val get_raw_backtrace_next_slot :
raw_backtrace_slot -> raw_backtrace_slot option
get_raw_backtrace_next_slot slot returns the next slot inlined, if any.
Sample code to iterate over all frames (inlined and non-inlined):
Since: 4.04.0
Exception slots
val exn_slot_id : exn -> int
Printexc.exn_slot_id returns an integer which uniquely identifies the constructor used to
create the exception value exn (in the current runtime).
Since: 4.02.0
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 string 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 arguments.
Conversion specifications have the following form:
% [flags] [width] [.precision] type
In short, a conversion specification consists in the % character, followed by optional
modifiers and a type which is made of one or two characters.
The types and their meanings are:
• o: convert an integer argument to unsigned octal. The flag # adds a 0 prefix to non
zero values.
• s: insert a string argument.
• S: convert a string argument to OCaml syntax (double quotes, escapes).
• c: insert a character argument.
• C: convert a character argument to OCaml syntax (single quotes, escapes).
• f: convert a floating-point argument to decimal notation, in the style dddd.ddd.
• F: convert a floating-point argument to OCaml syntax (dddd. or dddd.ddd or d.ddd
e+-dd). Converts to hexadecimal with the # flag (see h).
• 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). Moreover, any trailing zeros are removed from the
fractional part of the result and the decimal-point character is removed if there is no
fractional part remaining.
• h or H: convert a floating-point argument to hexadecimal notation, in the style
0xh.hhhh p+-dd (hexadecimal mantissa, exponent in decimal and denotes a power of
2).
• B: convert a boolean argument to the string true or false
• b: convert a boolean argument (deprecated; do not use in new programs).
• ld, li, lu, lx, lX, lo: convert an int32 argument to the format specified by the
second letter (decimal, hexadecimal, etc).
• nd, ni, nu, nx, nX, no: convert a nativeint argument to the format specified by the
second letter.
• Ld, Li, Lu, Lx, LX, Lo: convert an int64 argument to the format specified by the
second letter.
• a: user-defined printer. Take 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 inserted in the output of fprintf at the current point.
• t: same as %a, but take only one argument (with type out_channel -> unit) and
apply it to outchan.
• { fmt %}: convert a format string argument to its type digest. The argument must
have the same type as the internal format string fmt.
• ( fmt %): format string substitution. Take a format string argument and substitute it
to the internal format string fmt to print following arguments. The argument must
have the same type as the internal format string fmt.
• !: take no argument and flush the output.
• %: take no argument and output one % character.
Chapter 25. The standard library 699
The optional width is an integer indicating the minimal width of the result. For instance,
%6d prints an integer, prefixing it with spaces to fill at least 6 characters.
The optional precision is a dot . followed by an integer indicating how many digits follow
the decimal point in the %f, %e, %E, %h, and %H conversions or the maximum number of
significant digits to appear for the %F, %g and %G conversions. For instance, %.4f prints a
float with 4 fractional digits.
The integer in a width or precision can also be specified as *, in which case an extra
integer argument is taken to specify the corresponding width or precision. This integer
argument precedes immediately the argument to print. For instance, %.*f prints a float
with as many fractional digits as the value of the argument given before the float.
val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a
Same as Printf.fprintf[25.38], but instead of printing on an output channel, append the
formatted arguments to the given extensible buffer (see module Buffer[25.7]).
val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a
Same as Printf.fprintf[25.38], but does not print anything. Useful to ignore some
material when conditionally printing.
Since: 3.10.0
val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a
700
Same as Printf.bprintf[25.38], but does not print anything. Useful to ignore some
material when conditionally printing.
Since: 4.11.0
val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a
Same as kfprintf above, but does not print anything. Useful to ignore some material when
conditionally printing.
Since: 4.01.0
val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a
Same as sprintf above, but instead of returning the string, passes it to the first argument.
Since: 3.09.0
val kbprintf :
(Buffer.t -> 'd) ->
Buffer.t -> ('a, Buffer.t, unit, 'd) format4 -> 'a
Same as bprintf, but instead of returning immediately, passes the buffer to its first
argument at the end of printing.
Since: 3.10.0
val ikbprintf :
(Buffer.t -> 'd) ->
Buffer.t -> ('a, Buffer.t, unit, 'd) format4 -> 'a
Same as kbprintf above, but does not print anything. Useful to ignore some material when
conditionally printing.
Since: 4.11.0
Deprecated
val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a
A deprecated synonym for ksprintf.
Chapter 25. The standard library 701
type 'a t
The type of queues containing elements of type 'a.
exception Empty
Raised when Queue.take[25.39] or Queue.peek[25.39] is applied to an empty queue.
val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
fold f accu q is equivalent to List.fold_left f accu l, where l is the list of q’s
elements. The queue remains unchanged.
Iterators
val to_seq : 'a t -> 'a Seq.t
Iterate on the queue, in front-to-back order. The behavior is not defined if the queue is
modified during the iteration.
Since: 4.07
Basic functions
val init : int -> unit
Initialize the generator, using the argument as a seed. The same seed will always yield the
same sequence of numbers.
Advanced functions
The functions from module Random.State[25.40] manipulate the current state of the random gen-
erator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded
program, without interference from other parts of the program.
module State :
sig
type t
The type of PRNG states.
end
val get_state : unit -> State.t
Return the current state of the generator used by the basic functions.
Results
type ('a, 'e) t = ('a, 'e) result =
| Ok of 'a
| Error of 'e
The type for result values. Either a value Ok v or an error Error e.
val join : (('a, 'e) result, 'e) result -> ('a, 'e) result
706
val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result
map f r is Ok (f v) if r is Ok v and r if r is Error _.
val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result
map_error f r is Error (f e) if r is Error e and r if r is Ok _.
val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c
fold ~ok ~error r is ok v if r is Ok v and error e if r is Error e.
val iter : ('a -> unit) -> ('a, 'e) result -> unit
iter f r is f v if r is Ok v and () otherwise.
val iter_error : ('e -> unit) -> ('a, 'e) result -> unit
iter_error f r is f e if r is Error e and () otherwise.
val equal :
ok:('a -> 'a -> bool) ->
error:('e -> 'e -> bool) ->
('a, 'e) result -> ('a, 'e) result -> bool
equal ~ok ~error r0 r1 tests equality of r0 and r1 using ok and error to respectively
compare values wrapped by Ok _ and Error _.
val compare :
ok:('a -> 'a -> int) ->
error:('e -> 'e -> int) ->
('a, 'e) result -> ('a, 'e) result -> int
compare ~ok ~error r0 r1 totally orders r0 and r1 using ok and error to respectively
compare values wrapped by Ok _ and Error _. Ok _ values are smaller than Error
_ values.
Chapter 25. The standard library 707
Converting
val to_option : ('a, 'e) result -> 'a option
to_option r is r as an option, mapping Ok v to Some v and Error _ to None.
Introduction
Functional input with format strings
The module Scanf[25.42] provides formatted input functions or scanners.
The formatted input functions can read from any kind of input, including strings, files, or
anything that can return characters. The more general source of characters is named a formatted
input channel (or scanning buffer) and has type Scanf.Scanning.in_channel[25.42]. The more
general formatted input function reads from any scanning buffer and is named bscanf.
Generally speaking, the formatted input functions have 3 arguments:
• the second argument is a format string that specifies the values to read,
• the third argument is a receiver function that is applied to the values read.
Hence, a typical call to the formatted input function Scanf.bscanf[25.42] is bscanf ic fmt
f, where:
• fmt is a format string (the same format strings as those used to print material with module
Printf[25.38] or Format[25.18]),
• f is a function that has as many arguments as the number of values to read in the input
according to fmt.
708
A simple example
As suggested above, the expression bscanf ic "%d" f reads a decimal integer n from the source
of characters ic and returns f n.
For instance,
then bscanf Scanning.stdin "%d" f reads an integer n from the standard input and returns f
n (that is n + 1). Thus, if we evaluate bscanf stdin "%d" f, and then enter 41 at the keyboard,
the result we get is 42.
end
fmt f applies f to the arguments specified by fmt, reading those arguments from
stdin[24.2] as expected.
If the format fmt has some %r indications, the corresponding formatted input functions
must be provided before receiver function f. For instance, if read_elem is an input function
for values of type t, then bscanf ic "%r;" read_elem f reads a value v of type t followed
by a ';' character, and returns f v.
Since: 3.10.0
• conversion specifications, each of which causes reading and conversion of one argument for
the function f (see [25.42]),
1 when reading an input with various whitespace in it, such as Price = 1 $, Price = 1 $, or even
Price=1$.
• i: reads an optionally signed integer (usual input conventions for decimal (0-9+), hexadec-
imal (0x[0-9a-f]+ and 0X[0-9A-F]+), octal (0o[0-7]+), and binary (0b[0-1]+) notations
are understood).
• s: reads a string argument that spreads as much as possible, until the following bounding
condition holds:
Hence, this conversion always succeeds: it returns an empty string if the bounding condition
holds when the scan begins.
• S: reads a delimited string argument (delimiters and special escaped characters follow the
lexical conventions of OCaml).
• c: reads a single character. To test the current input character without reading it, specify
a null field width, i.e. use specification %0c. Raise Invalid_argument, if the field width
specification is greater than 1.
• C: reads a single delimited character (delimiters and special escaped characters follow the
lexical conventions of OCaml).
• F: reads a floating point number according to the lexical conventions of OCaml (hence the
decimal point is mandatory if the exponent part is not mentioned).
• b: reads a boolean argument (for backward compatibility; do not use in new programs).
• ld, li, lu, lx, lX, lo: reads an int32 argument to the format specified by the second letter
for regular integers.
• nd, ni, nu, nx, nX, no: reads a nativeint argument to the format specified by the second
letter for regular integers.
• Ld, Li, Lu, Lx, LX, Lo: reads an int64 argument to the format specified by the second letter
for regular integers.
• [ range ]: reads characters that matches one of the characters mentioned in the range of
characters range (or not mentioned in it, if the range starts with ^). Reads a string that can
be empty, if the next input character does not match the range. The set of characters from
c1 to c2 (inclusively) is denoted by c1-c2. Hence, %[0-9] returns a string representing a
decimal number or an empty string if no decimal digit is found; similarly, %[0-9a-f] returns
a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the
first character of the range (or just after the ^ in case of range negation); hence []] matches
a ] character and [^]] matches any character that is not ]. Use %% and %@ to include a % or
a @ in a range.
• r: user-defined reader. Takes the next ri formatted input function and applies it to the
scanning buffer ib to read the next argument. The input function ri must therefore have
type Scanning.in_channel -> 'a and the argument read has type 'a.
• { fmt %}: reads a format string argument. The format string read must have the same type
as the format string specification fmt. For instance, "%{ %i %}" reads any format string
that can read a value of type int; hence, if s is the string "fmt:\"number is %u\"", then
Scanf.sscanf s "fmt: %{%i%}" succeeds and returns the format string "number is %u".
• ( fmt %): scanning sub-format substitution. Reads a format string rf in the input, then goes
on scanning with rf instead of scanning with fmt. The format string rf must have the same
type as the format string specification fmt that it replaces. For instance, "%( %i %)" reads
any format string that can read a value of type int. The conversion returns the format string
read rf, and then a value read using rf. Hence, if s is the string "\"%4d\"1234.00", then
Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i) evaluates to ("%4d", 1234). This be-
haviour is not mere format substitution, since the conversion returns the format string read
as additional argument. If you need pure format substitution, use special flag _ to discard the
extraneous argument: conversion %_( fmt %) reads a format string rf and then behaves the
same as format string rf. Hence, if s is the string "\"%4d\"1234.00", then Scanf.sscanf
s "%_(%i%)" is simply equivalent to Scanf.sscanf "1234.00" "%4d".
• ,: does nothing.
Following the % character that introduces a conversion, there may be the special flag _: the
conversion that follows occurs as usual, but the resulting value is discarded. For instance, if f is
the function fun i -> i + 1, and s is the string "x = 1", then Scanf.sscanf s "%_s = %i" f
returns 2.
The field width is composed of an optional integer literal indicating the maximal width of the
token to read. For instance, %6d reads an integer, having at most 6 decimal digits; %4f reads a float
with at most 4 characters; and %8[\000-\255] returns the next 8 characters (or all the characters
still available, if fewer than 8 characters are available in the input).
Notes:
• as mentioned above, a %s conversion always succeeds, even if there is nothing to read in the
input: in this case, it simply returns "".
• in addition to the relevant digits, '_' characters may appear inside numbers (this is reminis-
cent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range
conversion facility instead of the number conversions.
• the scanf facility is not intended for heavy duty lexical analysis and parsing. If it appears
not expressive enough for your needs, several alternative exists: regular expressions (module
Str[28.1]), stream parsers, ocamllex-generated lexers, ocamlyacc-generated parsers.
• As usual in format strings, % and @ characters must be escaped using %% and %@; this rule
still holds within range specifications and scanning indications. For instance, format "%s@%%"
reads a string up to the next % character, and format "%s@%@" reads a string up to the next
@.
• The scanning indications introduce slight differences in the syntax of Scanf[25.42] format
strings, compared to those used for the Printf[25.38] module. However, the scanning in-
dications are similar to those used in the Format[25.18] module; hence, when producing
formatted text to be scanned by Scanf.bscanf[25.42], it is wise to use printing functions
from the Format[25.18] module (or, if you need to use functions from Printf[25.38], banish
or carefully double check the format strings that contain '@' characters).
Chapter 25. The standard library 715
• Raise End_of_file if the end of input is encountered while some more characters are needed
to read the current conversion specification.
Note:
val kscanf :
Scanning.in_channel ->
(Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner
Same as Scanf.bscanf[25.42], but takes an additional function argument ef that is called
in case of error: if the scanning process or some conversion fails, the scanning function
aborts and calls the error handling function ef with the formatted input channel and the
exception that aborted the scanning process as arguments.
val ksscanf :
string ->
(Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner
Same as Scanf.kscanf[25.42] but reads from the given string.
Since: 4.02.0
716
val sscanf_format :
string ->
('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g
Same as Scanf.bscanf_format[25.42], but reads from the given string.
Since: 3.09.0
val format_from_string :
string ->
('a, 'b, 'c, 'd, 'e, 'f) format6 ->
('a, 'b, 'c, 'd, 'e, 'f) format6
format_from_string s fmt converts a string argument to a format string, according to the
given format string fmt.
Since: 3.10.0
Raises Scan_failure if s, considered as a format string, does not have the same type as
fmt.
Deprecated
val fscanf : in_channel -> ('a, 'b, 'c, 'd) scanner
Deprecated. Scanf.fscanf is error prone and deprecated since 4.03.0.
This function violates the following invariant of the Scanf[25.42] module: To preserve
scanning semantics, all scanning functions defined in Scanf[25.42] must read from a user
defined Scanf.Scanning.in_channel[25.42] formatted input channel.
If you need to read from a in_channel[24.2] input channel ic, simply define a
Scanf.Scanning.in_channel[25.42] formatted input channel as in let ib =
Scanning.from_channel ic, then use Scanf.bscanf ib as usual.
val kfscanf :
in_channel ->
(Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner
Deprecated. Scanf.kfscanf is error prone and deprecated since 4.03.0.
val filter_map : ('a -> 'b option) -> 'a t -> 'b t
Apply the function to every element; if f x = None then x is dropped; if f x = Some y
then y is returned. This transformation is lazy, it only applies when the result is traversed.
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
Traverse the sequence from left to right, combining each element with the accumulator using
the given function. The traversal happens immediately and will not terminate on infinite
sequences.
Also see List.fold_left[25.28]
val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t
Build a sequence from a step function and an initial value. unfold f u returns empty if f u
returns None, or fun () -> Cons (x, unfold f y) if f u returns Some (x, y).
For example, unfold (function [] -> None | h::t -> Some (h,t)) l is equivalent to
List.to_seq l.
Since: 4.11
Chapter 25. The standard library 719
module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
0 -> Stdlib.compare y0 y1
| c -> c
end
let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
This creates a new module PairsSet, with a new type PairsSet.t of sets of int * int.
end
module type S =
sig
type elt
720
type t
The type of sets.
val empty : t
The empty set.
Total ordering between sets. Can be used as the ordering function for doing sets of sets.
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
fold f s init computes (f xN ... (f x2 (f x1 init))...), where x1 ... xN
are the elements of s, in increasing order.
filter_map f s returns the set of all v such that f x = Some v for some element x of
s.
For example,
filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s.
If no element of s is changed or dropped by f (if f x = Some x for each element x),
then s is returned unchanged: the result of the function is then physically equal to s.
Since: 4.11.0
Iterators
val to_seq_from : elt -> t -> elt Seq.t
to_seq_from x s iterates on a subset of the elements of s in ascending order, from x
or above.
Since: 4.07
end
module Make :
functor (Ord : OrderedType) -> S with type elt = Ord.t
Functor building an implementation of the set structure given a totally ordered type.
Chapter 25. The standard library 725
type 'a t
The type of stacks containing elements of type 'a.
exception Empty
Raised when Stack.pop[25.45] or Stack.top[25.45] is applied to an empty stack.
val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
fold f accu s is (f (... (f (f accu x1) x2) ...) xn) where x1 is the top of the
stack, x2 the second element, and xn the bottom element. The stack is unchanged.
Since: 4.03
open StdLabels
module Array :
ArrayLabels
module Bytes :
BytesLabels
module List :
Chapter 25. The standard library 727
ListLabels
module String :
StringLabels
type 'a t
The type of streams holding values of type 'a.
exception Failure
Raised by parsers when none of the first components of the stream patterns is accepted.
Stream builders
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 <value> for a value or None to specify the end of the stream.
Do note that the indices passed to f may not start at 0 in the general case. For example, [<
'0; '1; Stream.from f >] would call f the first time with count 2.
Stream iterator
val iter : ('a -> unit) -> '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.
Raises Stream.Failure if the stream is empty.
Useful functions
val peek : 'a t -> 'a option
Return Some of "the first element" of the stream, or None if the stream is empty.
positions 0 1 2 3 4 n-1 n
+---+---+---+---+ +-----+
indices | 0 | 1 | 2 | 3 | ... | n-1 |
+---+---+---+---+ +-----+
Chapter 25. The standard library 729
• An index i of s is an integer in the range [0;n-1]. It represents the ith byte (character) of s
which can be accessed using the constant time string indexing operator s.[i].
• A position i of s is an integer in the range [0;n]. It represents either the point at the beginning
of the string, or the point between two indices, or the point at the end of the string. The ith
byte index is between position i and i+1.
Two integers start and len are said to define a valid substring of s if len >= 0 and start,
start+len are positions of s.
Unicode text. Strings being arbitrary sequences of bytes, they can hold any kind of textual
encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8.
This is the encoding used by Unicode escapes in string literals. For example the string "\u{1F42B}"
is the UTF-8 encoding of the Unicode character U+1F42B.
Past mutability. OCaml strings used to be modifiable in place, for instance via the
String.set[25.48] and String.blit[25.48] functions. This use is nowadays only possible when
the compiler is put in "unsafe-string" mode by giving the -unsafe-string command-line option.
This compatibility mode makes the types string and bytes (see Bytes.t[25.8]) interchangeable
so that functions expecting byte sequences can also accept strings as arguments and modify them.
The distinction between bytes and string was introduced in OCaml 4.02, and the "unsafe-
string" compatibility mode was the default until OCaml 4.05. Starting with 4.06, the compatibility
mode is opt-in; we intend to remove the option in the future.
The labeled version of this module can be used as described in the StdLabels[25.46] module.
Strings
type t = string
The type for strings.
Return a new string that contains the same bytes as the given byte sequence.
Since: 4.13.0
Concatenating
Note. The (^)[24.2] binary operator concatenates two strings.
val concat : string -> string list -> string
concat sep ss concatenates the list of strings ss, inserting the separator string sep
between each.
Raises Invalid_argument if the result is longer than Sys.max_string_length[25.50]
bytes.
Extracting substrings
val sub : string -> int -> int -> string
sub s pos len is a string of length len, containing the substring of s that starts at
position pos and has length len.
Raises Invalid_argument if pos and len do not designate a valid substring of s.
Transforming
val map : (char -> char) -> string -> string
map f s is the string resulting from applying f to all the characters of s in increasing order.
Since: 4.00.0
val mapi : (int -> char -> char) -> string -> string
mapi f s is like String.map[25.48] but the index of the character is also passed to f.
Since: 4.02.0
val fold_left : ('a -> char -> 'a) -> 'a -> string -> 'a
fold_left f x s computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1], where n is
the length of the string s.
Since: 4.13.0
val fold_right : (char -> 'a -> 'a) -> string -> 'a -> 'a
fold_right f s x computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...)), where n
is the length of the string s.
Since: 4.13.0
Traversing
val iter : (char -> unit) -> string -> unit
iter f s applies function f in turn to all the characters of s. It is equivalent to f s.[0];
f s.[1]; ...; f s.[length s - 1]; ().
val iteri : (int -> char -> unit) -> string -> unit
iteri is like String.iter[25.48], but the function is also given the corresponding character
index.
Since: 4.00.0
Searching
val index_from : string -> int -> char -> int
index_from s i c is the index of the first occurrence of c in s after position i.
Raises
val index_from_opt : string -> int -> char -> int option
734
index_from_opt s i c is the index of the first occurrence of c in s after position i (if any).
Since: 4.05
Raises Invalid_argument if i is not a valid position in s.
val rindex_from_opt : string -> int -> char -> int option
rindex_from_opt s i c is the index of the last occurrence of c in s before position i+1 (if
any).
Since: 4.05
Raises Invalid_argument if i+1 is not a valid position in s.
Deprecated functions
val create : int -> bytes
Deprecated. This is a deprecated alias of
Bytes.create[25.8]/BytesLabels.create[25.9].create n returns a fresh byte sequence of
length n. The sequence is uninitialized and contains arbitrary bytes.
Raises Invalid_argument if n < 0 or n > Sys.max_string_length[25.50].
val blit : string -> int -> bytes -> int -> int -> unit
blit src src_pos dst dst_pos len copies len bytes from the string src, starting at
index src_pos, to byte sequence dst, starting at character number dst_pos.
Raises Invalid_argument if src_pos and len do not designate a valid range of src, or if
dst_pos and len do not designate a valid range of dst.
val fill : bytes -> int -> int -> char -> unit
Deprecated. This is a deprecated alias of Bytes.fill[25.8]/BytesLabels.fill[25.9].fill s
pos len c modifies byte sequence s in place, replacing len bytes by c, starting at pos.
Raises Invalid_argument if pos and len do not designate a valid substring of s.
positions 0 1 2 3 4 n-1 n
+---+---+---+---+ +-----+
indices | 0 | 1 | 2 | 3 | ... | n-1 |
+---+---+---+---+ +-----+
• An index i of s is an integer in the range [0;n-1]. It represents the ith byte (character) of s
which can be accessed using the constant time string indexing operator s.[i].
• A position i of s is an integer in the range [0;n]. It represents either the point at the beginning
of the string, or the point between two indices, or the point at the end of the string. The ith
byte index is between position i and i+1.
Two integers start and len are said to define a valid substring of s if len >= 0 and start,
start+len are positions of s.
Unicode text. Strings being arbitrary sequences of bytes, they can hold any kind of textual
encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8.
This is the encoding used by Unicode escapes in string literals. For example the string "\u{1F42B}"
is the UTF-8 encoding of the Unicode character U+1F42B.
Past mutability. OCaml strings used to be modifiable in place, for instance via the
String.set[25.48] and String.blit[25.48] functions. This use is nowadays only possible when
the compiler is put in "unsafe-string" mode by giving the -unsafe-string command-line option.
This compatibility mode makes the types string and bytes (see Bytes.t[25.8]) interchangeable
so that functions expecting byte sequences can also accept strings as arguments and modify them.
The distinction between bytes and string was introduced in OCaml 4.02, and the "unsafe-
string" compatibility mode was the default until OCaml 4.05. Starting with 4.06, the compatibility
mode is opt-in; we intend to remove the option in the future.
The labeled version of this module can be used as described in the StdLabels[25.46] module.
Strings
type t = string
The type for strings.
Concatenating
Note. The (^)[24.2] binary operator concatenates two strings.
val concat : sep:string -> string list -> string
concat ~sep ss concatenates the list of strings ss, inserting the separator string sep
between each.
Raises Invalid_argument if the result is longer than Sys.max_string_length[25.50]
bytes.
Extracting substrings
val sub : string -> pos:int -> len:int -> string
sub s ~pos ~len is a string of length len, containing the substring of s that starts at
position pos and has length len.
Raises Invalid_argument if pos and len do not designate a valid substring of s.
• Concatenating its elements using sep as a separator returns a string equal to the input
(concat (make 1 sep) (split_on_char sep s) = s).
• No string in the result contains the sep character.
Since: 4.05.0
Transforming
val map : f:(char -> char) -> string -> string
map f s is the string resulting from applying f to all the characters of s in increasing order.
Since: 4.00.0
val mapi : f:(int -> char -> char) -> string -> string
mapi ~f s is like StringLabels.map[25.49] but the index of the character is also passed to
f.
Since: 4.02.0
val fold_left : f:('a -> char -> 'a) -> init:'a -> string -> 'a
fold_left f x s computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1], where n is
the length of the string s.
Since: 4.13.0
val fold_right : f:(char -> 'a -> 'a) -> string -> init:'a -> 'a
fold_right f s x computes f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...)), where n
is the length of the string s.
Since: 4.13.0
escaped s is s with special characters represented by escape sequences, following the lexical
conventions of OCaml.
All characters outside the US-ASCII printable range [0x20;0x7E] are escaped, as well as
backslash (0x2F) and double-quote (0x22).
The function Scanf.unescaped[25.42] is a left inverse of escaped, i.e. Scanf.unescaped
(escaped s) = s for any string s (unless escaped s fails).
Raises Invalid_argument if the result is longer than Sys.max_string_length[25.50]
bytes.
Traversing
val iter : f:(char -> unit) -> string -> unit
iter ~f s applies function f in turn to all the characters of s. It is equivalent to f s.[0];
f s.[1]; ...; f s.[length s - 1]; ().
val iteri : f:(int -> char -> unit) -> string -> unit
iteri is like StringLabels.iter[25.49], but the function is also given the corresponding
character index.
Since: 4.00.0
Chapter 25. The standard library 743
Searching
val index_from : string -> int -> char -> int
index_from s i c is the index of the first occurrence of c in s after position i.
Raises
val index_from_opt : string -> int -> char -> int option
index_from_opt s i c is the index of the first occurrence of c in s after position i (if any).
Since: 4.05
Raises Invalid_argument if i is not a valid position in s.
val rindex_from_opt : string -> int -> char -> int option
rindex_from_opt s i c is the index of the last occurrence of c in s before position i+1 (if
any).
Since: 4.05
Raises Invalid_argument if i+1 is not a valid position in s.
Deprecated functions
val create : int -> bytes
Deprecated. This is a deprecated alias of
Bytes.create[25.8]/BytesLabels.create[25.9].create n returns a fresh byte sequence of
length n. The sequence is uninitialized and contains arbitrary bytes.
Raises Invalid_argument if n < 0 or n > Sys.max_string_length[25.50].
val blit :
src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
blit ~src ~src_pos ~dst ~dst_pos ~len copies len bytes from the string src, starting
at index src_pos, to byte sequence dst, starting at character number dst_pos.
Raises Invalid_argument if src_pos and len do not designate a valid range of src, or if
dst_pos and len do not designate a valid range of dst.
val fill : bytes -> pos:int -> len:int -> char -> unit
Chapter 25. The standard library 745
Return the names of all files present in the given directory. Names denoting the current
directory and the parent directory ("." and ".." in Unix) are not returned. Each string in
the result is a file name rather than a complete path. There is no guarantee that the name
strings in the resulting array will appear in any specific order; they are not, in particular,
guaranteed to appear in alphabetical order.
• "Unix" (for all Unix versions, including Linux and Mac OS X),
• "Win32" (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
• "Cygwin" (for MS-Windows, OCaml compiled with Cygwin).
type backend_type =
| Native
| Bytecode
| Other of string
Currently, the official distribution only supports Native and Bytecode, but it can be other
backends with alternative compilers, for example, javascript.
Since: 4.04.0
Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64.
Signal handling
type signal_behavior =
| Signal_default
| Signal_ignore
| Signal_handle of (int -> unit)
What to do when receiving a signal:
Chapter 25. The standard library 751
exception Break
Exception raised on interactive interrupt if Sys.catch_break[25.50] is on.
Optimization
val opaque_identity : 'a -> 'a
For the purposes of optimization, opaque_identity behaves like an unknown (and thus
possibly side-effecting) function.
At runtime, opaque_identity disappears altogether.
A typical use of this function is to prevent pure computations from being optimized
away in benchmarking loops. For example:
Since: 4.03.0
module Immediate64 :
sig
This module allows to define a type t with the immediate64 attribute. This attribute means
that the type is immediate on 64 bit architectures. On other architectures, it might or might
not be immediate.
module type Non_immediate =
sig
type t
end
module type Immediate =
sig
type t
end
module Make :
functor (Immediate : Immediate) -> functor (Non_immediate : Non_immediate)
-> sig
type t
type 'a repr =
| Immediate : Sys.Immediate64.Immediate.t repr
| Non_immediate : Sys.Immediate64.Non_immediate.t repr
val repr : t repr
end
end
Chapter 25. The standard library 755
type t
The type for Unicode characters.
A value of this type represents a Unicode scalar
value[http://unicode.org/glossary/#unicode_scalar_value] which is an integer in the
ranges 0x0000. . .0xD7FF or 0xE000. . .0x10FFFF.
val min : t
min is U+0000.
val max : t
max is U+10FFFF.
val bom : t
bom is U+FEFF, the byte order mark[http://unicode.org/glossary/#byte_order_mark]
(BOM) character.
Since: 4.06.0
val rep : t
rep is U+FFFD, the
replacement[http://unicode.org/glossary/#replacement_character] character.
Since: 4.06.0
to_int u is u as an integer.
Low-level functions
type 'a t
The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the
garbage collector may erase whenever the value is not used any more (through normal
pointers) by the program. Note that finalisation functions are run before the weak pointers
are erased, because the finalisation functions can make values alive again (before 4.03 the
finalisation functions were run after).
A weak pointer is said to be full if it points to a value, empty if the value was erased by the
GC.
Notes:
val set : 'a t -> int -> 'a option -> unit
Weak.set ar n (Some el) sets the nth cell of ar to be a (full) pointer to el; Weak.set ar
n None sets the nth cell of ar to empty.
Raises Invalid_argument if n is not in the range 0 to Weak.length[25.53] a - 1.
val fill : 'a t -> int -> int -> 'a option -> unit
Weak.fill ar ofs len el sets to el all pointers of ar from ofs to ofs + len - 1.
Raises Invalid_argument if ofs and len do not designate a valid subarray of a.
val blit : 'a t -> int -> 'a t -> int -> int -> unit
Weak.blit ar1 off1 ar2 off2 len copies len weak pointers from ar1 (starting at off1)
to ar2 (starting at off2). It works correctly even if ar1 and ar2 are the same.
Raises Invalid_argument if off1 and len do not designate a valid subarray of ar1, or if
off2 and len do not designate a valid subarray of ar2.
type t
The type of tables that contain elements of type data. Note that weak hash sets cannot
be marshaled using output_value[24.2] or the functions of the Marshal[25.31] module.
val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
fold f t init computes (f d1 (... (f dN init))) where d1 ... dN are the
elements of t in some unspecified order. It is not specified what happens if f tries to
change t itself.
Return statistics on the table. The numbers are, in order: table length, number of
entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest
bucket length.
end
module Make :
functor (H : Hashtbl.HashedType) -> S with type data = H.t
Functor building an implementation of the weak hash set structure. H.equal can’t be the
physical equality, since only shallow copies of the elements in the set are given to it.
This chapter describes the OCaml front-end, which declares the abstract syntax tree used by the
compiler, provides a way to parse, print and pretty-print OCaml code, and ultimately allows one
to write abstract syntax tree preprocessors invoked via the -ppx flag (see chapters 11 and 14).
It is important to note that the exported front-end interface follows the evolution of the OCaml
language and implementation, and thus does not provide any backwards compatibility guarantees.
The front-end is a part of compiler-libs library. Programs that use the compiler-libs library
should be built as follows:
Use of the ocamlfind utility is recommended. However, if this is not possible, an alternative
method may be used:
For interactive use of the compiler-libs library, start ocaml and type
#load "compiler-libs/ocamlcommon.cma";;.
open Asttypes
open Parsetree
open Ast_mapper
761
762
let () =
register "ppx_test" test_mapper
This -ppx rewriter, which replaces [%test] in expressions with the constant 42, can be compiled
using ocamlc -o ppx_test -I +compiler-libs ocamlcommon.cma ppx_test.ml.
Warning: this module is unstable and part of compiler-libs[26].
command-line options are automatically synchronized between the calling tool and the ppx
preprocessor: Clflags.include_dirs[??], Load_path[??], Clflags.open_modules[??],
Clflags.for_package[??], Clflags.debug[??].
Registration API
val register_function : (string -> (string list -> mapper) -> unit) ref
val register : string -> (string list -> mapper) -> unit
Apply the register_function. The default behavior is to run the mapper immediately,
taking arguments from the process command line. This is to support a scenario where a
mapper is linked as a stand-alone executable.
It is possible to overwrite the register_function to define "-ppx drivers", which combine
several mappers in a single process. Typically, a driver starts by defining
register_function to a custom implementation, then lets ppx rewriters (linked statically
or dynamically) register themselves, and then run all or some of them. It is also possible to
have -ppx drivers apply rewriters to only specific parts of an AST.
The first argument to register is a symbolic name to be used by the ppx driver.
val add_ppx_context_sig :
tool_name:string -> Parsetree.signature -> Parsetree.signature
Same as add_ppx_context_str, but for signatures.
val drop_ppx_context_str :
restore:bool -> Parsetree.structure -> Parsetree.structure
Drop the ocaml.ppx.context attribute from a structure. If restore is true, also restore the
associated data in the current process.
val drop_ppx_context_sig :
restore:bool -> Parsetree.signature -> Parsetree.signature
Same as drop_ppx_context_str, but for signatures.
Cookies
Cookies are used to pass information from a ppx processor to a further invocation of itself, when
called from the OCaml toplevel (or other tools that support cookies).
val set_cookie : string -> Parsetree.expression -> unit
val get_cookie : string -> Parsetree.expression option
type constant =
| Const_int of int
| Const_char of char
| Const_string of string * Location.t * string option
| Const_float of string
| Const_int32 of int32
| Const_int64 of int64
| Const_nativeint of nativeint
type rec_flag =
| Nonrecursive
766
| Recursive
type direction_flag =
| Upto
| Downto
type private_flag =
| Private
| Public
type mutable_flag =
| Immutable
| Mutable
type virtual_flag =
| Virtual
| Concrete
type override_flag =
| Override
| Fresh
type closed_flag =
| Closed
| Open
type label = string
type arg_label =
| Nolabel
| Labelled of string
| Optional of string
type 'a loc = 'a Location.loc =
{ txt : 'a ;
loc : Location.t ;
}
type variance =
| Covariant
| Contravariant
| NoVariance
type injectivity =
| Injective
| NoInjectivity
type t = Warnings.loc =
Chapter 26. The compiler front-end 767
{ loc_start : Lexing.position ;
loc_end : Lexing.position ;
loc_ghost : bool ;
}
Note on the use of Lexing.position in this module. If pos_fname = "", then use !input_name
instead. If pos_lnum = -1, then pos_bol = 0. Use pos_cnum and re-parse the file to get the line
and character numbers. Else all fields are correct.
val none : t
An arbitrary value of type t; describes an empty ghost range.
Input info
val input_name : string ref
val input_lexbuf : Lexing.lexbuf option ref
val input_phrase_buffer : Buffer.t option ref
768
Toplevel-specific functions
val echo_eof : unit -> unit
val reset : unit -> unit
Printing locations
val rewrite_absolute_path : string -> string
rewrite absolute path to honor the BUILD_PATH_PREFIX_MAP variable
(https://reproducible-builds.org/specs/build-path-prefix-map/) if it is set.
Printing a report
val print_report : Format.formatter -> report -> unit
Display an error or warning report.
Reporting warnings
Converting a Warnings.t into a report
val report_warning : t -> Warnings.t -> report option
report_warning loc w produces a report for the given warning w, or None if the warning is
not to be printed.
Printing warnings
val formatter_for_warnings : Format.formatter ref
val print_warning : t -> Format.formatter -> Warnings.t -> unit
Prints a warning. This is simply the composition of report_warning and print_report.
Reporting alerts
Converting an Alert.t into a report
val report_alert : t -> Warnings.alert -> report option
report_alert loc w produces a report for the given alert w, or None if the alert is not to
be printed.
Printing alerts
val print_alert : t -> Format.formatter -> Warnings.alert -> unit
Prints an alert. This is simply the composition of report_alert and print_report.
val deprecated : ?def:t -> ?use:t -> t -> string -> unit
Prints a deprecation alert.
Reporting errors
type error = report
An error is a report which report_kind must be Report_error.
val error : ?loc:t -> ?sub:msg list -> string -> error
val errorf :
?loc:t ->
?sub:msg list ->
('a, Format.formatter, unit, error) format4 -> 'a
val error_of_printer :
?loc:t ->
?sub:msg list ->
(Format.formatter -> 'a -> unit) -> 'a -> error
val error_of_printer_file : (Format.formatter -> 'a -> unit) -> 'a -> error
exception Already_displayed_error
Raising Already_displayed_error signals an error which has already been printed. The
exception will be caught, but nothing will be printed
772
val raise_errorf :
?loc:t ->
?sub:msg list ->
('a, Format.formatter, unit, 'b) format4 -> 'a
val report_exception : Format.formatter -> exn -> unit
Reraise the exception if it is unknown.
type t =
| Lident of string
| Ldot of t * string
| Lapply of t * t
val flatten : t -> string list
val unflatten : string list -> t option
For a non-empty list l, unflatten l is Some lid where lid is the long identifier created by
concatenating the elements of l with Ldot. unflatten [] is None.
This function parse syntactically valid path for a type or a module type. For instance, A, t,
M.t and F(X).t are valid. Contrarily, (.%()) or [] are both rejected.
In path for type and module types, only operators and special constructors are rejected.
type constant =
| Pconst_integer of string * char option
| Pconst_char of char
| Pconst_string of string * Location.t * string option
| Pconst_float of string * char option
type location_stack = Location.t list
Extension points
type attribute =
{ attr_name : string Asttypes.loc ;
attr_payload : payload ;
attr_loc : Location.t ;
}
type extension = string Asttypes.loc * payload
type attributes = attribute list
type payload =
| PStr of structure
| PSig of signature
| PTyp of core_type
| PPat of pattern * expression option
Core language
type core_type =
{ ptyp_desc : core_type_desc ;
ptyp_loc : Location.t ;
ptyp_loc_stack : location_stack ;
ptyp_attributes : attributes ;
}
type core_type_desc =
| Ptyp_any
| Ptyp_var of string
Chapter 26. The compiler front-end 775
}
type type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list
| Ptype_open
type label_declaration =
{ pld_name : string Asttypes.loc ;
pld_mutable : Asttypes.mutable_flag ;
pld_type : core_type ;
pld_loc : Location.t ;
pld_attributes : attributes ;
}
type constructor_declaration =
{ pcd_name : string Asttypes.loc ;
pcd_args : constructor_arguments ;
pcd_res : core_type option ;
pcd_loc : Location.t ;
pcd_attributes : attributes ;
}
type constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
type type_extension =
{ ptyext_path : Longident.t Asttypes.loc ;
ptyext_params : (core_type * (Asttypes.variance * Asttypes.injectivity)) list ;
ptyext_constructors : extension_constructor list ;
ptyext_private : Asttypes.private_flag ;
ptyext_loc : Location.t ;
ptyext_attributes : attributes ;
}
type extension_constructor =
{ pext_name : string Asttypes.loc ;
pext_kind : extension_constructor_kind ;
pext_loc : Location.t ;
pext_attributes : attributes ;
}
type type_exception =
{ ptyexn_constructor : extension_constructor ;
ptyexn_loc : Location.t ;
ptyexn_attributes : attributes ;
}
type extension_constructor_kind =
| Pext_decl of constructor_arguments * core_type option
Chapter 26. The compiler front-end 779
Class language
type class_type =
{ pcty_desc : class_type_desc ;
pcty_loc : Location.t ;
pcty_attributes : attributes ;
}
type class_type_desc =
| Pcty_constr of Longident.t Asttypes.loc * core_type list
| Pcty_signature of class_signature
| Pcty_arrow of Asttypes.arg_label * core_type * class_type
| Pcty_extension of extension
| Pcty_open of open_description * class_type
type class_signature =
{ pcsig_self : core_type ;
pcsig_fields : class_type_field list ;
}
type class_type_field =
{ pctf_desc : class_type_field_desc ;
pctf_loc : Location.t ;
pctf_attributes : attributes ;
}
type class_type_field_desc =
| Pctf_inherit of class_type
| Pctf_val of (Asttypes.label Asttypes.loc * Asttypes.mutable_flag *
Asttypes.virtual_flag * core_type)
| Pctf_method of (Asttypes.label Asttypes.loc * Asttypes.private_flag *
Asttypes.virtual_flag * core_type)
| Pctf_constraint of (core_type * core_type)
| Pctf_attribute of attribute
| Pctf_extension of extension
type 'a class_infos =
{ pci_virt : Asttypes.virtual_flag ;
pci_params : (core_type * (Asttypes.variance * Asttypes.injectivity)) list ;
pci_name : string Asttypes.loc ;
pci_expr : 'a ;
pci_loc : Location.t ;
pci_attributes : attributes ;
}
type class_description = class_type class_infos
type class_type_declaration = class_type class_infos
type class_expr =
780
{ pcl_desc : class_expr_desc ;
pcl_loc : Location.t ;
pcl_attributes : attributes ;
}
type class_expr_desc =
| Pcl_constr of Longident.t Asttypes.loc * core_type list
| Pcl_structure of class_structure
| Pcl_fun of Asttypes.arg_label * expression option * pattern
* class_expr
| Pcl_apply of class_expr * (Asttypes.arg_label * expression) list
| Pcl_let of Asttypes.rec_flag * value_binding list * class_expr
| Pcl_constraint of class_expr * class_type
| Pcl_extension of extension
| Pcl_open of open_description * class_expr
type class_structure =
{ pcstr_self : pattern ;
pcstr_fields : class_field list ;
}
type class_field =
{ pcf_desc : class_field_desc ;
pcf_loc : Location.t ;
pcf_attributes : attributes ;
}
type class_field_desc =
| Pcf_inherit of Asttypes.override_flag * class_expr * string Asttypes.loc option
| Pcf_val of (Asttypes.label Asttypes.loc * Asttypes.mutable_flag *
class_field_kind)
| Pcf_method of (Asttypes.label Asttypes.loc * Asttypes.private_flag *
class_field_kind)
| Pcf_constraint of (core_type * core_type)
| Pcf_initializer of expression
| Pcf_attribute of attribute
| Pcf_extension of extension
type class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of Asttypes.override_flag * expression
type class_declaration = class_expr class_infos
Module language
type module_type =
{ pmty_desc : module_type_desc ;
pmty_loc : Location.t ;
pmty_attributes : attributes ;
Chapter 26. The compiler front-end 781
}
type module_type_desc =
| Pmty_ident of Longident.t Asttypes.loc
| Pmty_signature of signature
| Pmty_functor of functor_parameter * module_type
| Pmty_with of module_type * with_constraint list
| Pmty_typeof of module_expr
| Pmty_extension of extension
| Pmty_alias of Longident.t Asttypes.loc
type functor_parameter =
| Unit
| Named of string option Asttypes.loc * module_type
type signature = signature_item list
type signature_item =
{ psig_desc : signature_item_desc ;
psig_loc : Location.t ;
}
type signature_item_desc =
| Psig_value of value_description
| Psig_type of Asttypes.rec_flag * type_declaration list
| Psig_typesubst of type_declaration list
| Psig_typext of type_extension
| Psig_exception of type_exception
| Psig_module of module_declaration
| Psig_modsubst of module_substitution
| Psig_recmodule of module_declaration list
| Psig_modtype of module_type_declaration
| Psig_modtypesubst of module_type_declaration
| Psig_open of open_description
| Psig_include of include_description
| Psig_class of class_description list
| Psig_class_type of class_type_declaration list
| Psig_attribute of attribute
| Psig_extension of extension * attributes
type module_declaration =
{ pmd_name : string option Asttypes.loc ;
pmd_type : module_type ;
pmd_attributes : attributes ;
pmd_loc : Location.t ;
}
type module_substitution =
{ pms_name : string Asttypes.loc ;
pms_manifest : Longident.t Asttypes.loc ;
pms_attributes : attributes ;
782
pms_loc : Location.t ;
}
type module_type_declaration =
{ pmtd_name : string Asttypes.loc ;
pmtd_type : module_type option ;
pmtd_attributes : attributes ;
pmtd_loc : Location.t ;
}
type 'a open_infos =
{ popen_expr : 'a ;
popen_override : Asttypes.override_flag ;
popen_loc : Location.t ;
popen_attributes : attributes ;
}
type open_description = Longident.t Asttypes.loc open_infos
type open_declaration = module_expr open_infos
type 'a include_infos =
{ pincl_mod : 'a ;
pincl_loc : Location.t ;
pincl_attributes : attributes ;
}
type include_description = module_type include_infos
type include_declaration = module_expr include_infos
type with_constraint =
| Pwith_type of Longident.t Asttypes.loc * type_declaration
| Pwith_module of Longident.t Asttypes.loc * Longident.t Asttypes.loc
| Pwith_modtype of Longident.t Asttypes.loc * module_type
| Pwith_modtypesubst of Longident.t Asttypes.loc * module_type
| Pwith_typesubst of Longident.t Asttypes.loc * type_declaration
| Pwith_modsubst of Longident.t Asttypes.loc * Longident.t Asttypes.loc
type module_expr =
{ pmod_desc : module_expr_desc ;
pmod_loc : Location.t ;
pmod_attributes : attributes ;
}
type module_expr_desc =
| Pmod_ident of Longident.t Asttypes.loc
| Pmod_structure of structure
| Pmod_functor of functor_parameter * module_expr
| Pmod_apply of module_expr * module_expr
| Pmod_constraint of module_expr * module_type
| Pmod_unpack of expression
| Pmod_extension of extension
Chapter 26. The compiler front-end 783
Toplevel
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive
type toplevel_directive =
{ pdir_name : string Asttypes.loc ;
pdir_arg : directive_argument option ;
pdir_loc : Location.t ;
}
784
type directive_argument =
{ pdira_desc : directive_argument_desc ;
pdira_loc : Location.t ;
}
type directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
The unix library makes many Unix system calls and system-related library functions available to
OCaml 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.
Programs that use the unix library must be linked as follows:
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type
#load "unix.cma";;.
Windows:
A fairly complete emulation of the Unix system calls is provided in the Windows version
of OCaml. The end of this chapter gives more information on the functions that are not
supported under Windows.
785
786
Error report
type error =
| E2BIG
Argument list too long
| EACCES
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
Chapter 27. The unix library: Unix system calls 787
| 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
788
| EROFS
Read-only file system
| ESPIPE
Invalid seek e.g. on a pipe
| ESRCH
No such process
| EXDEV
Invalid link
| 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
| 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
Chapter 27. The unix library: Unix system calls 789
| 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
790
| EOVERFLOW
File size or position not representable
| EUNKNOWNERR of int
Unknown error
The type of error codes. Errors defined in the POSIX standard and additional errors from
UNIX98 and BSD. All other errors are mapped to EUNKNOWNERR.
Process handling
type process_status =
| WEXITED of int
The process terminated normally by exit; the argument is the return code.
| WSIGNALED of int
The process was killed by a signal; the argument is the signal number.
| WSTOPPED of int
The process was stopped by a signal; the argument is the signal number.
The termination status of a process. See module Sys[25.50] for the definitions of the
standard signal numbers. Note that they are not the numbers used by the OS.
type wait_flag =
| WNOHANG
Do not block if no child has died yet, but immediately return with a pid equal to 0.
| WUNTRACED
Report also the children that receive stop signals.
Flags for Unix.waitpid[27.1].
val execve : string -> string array -> string array -> 'a
Same as Unix.execv[27.1], except that the third argument provides the environment to the
program executed.
792
val execvpe : string -> string array -> string array -> 'a
Same as Unix.execve[27.1], except that the program is searched in the path.
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
794
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 (see Unix.umask[27.1]). Return a file descriptor on the named file.
val read : file_descr -> bytes -> int -> int -> int
read fd buf pos len reads len bytes from descriptor fd, storing them in byte sequence
buf, starting at position pos in buf. Return the number of bytes actually read.
Chapter 27. The unix library: Unix system calls 795
val write : file_descr -> bytes -> int -> int -> int
write fd buf pos len writes len bytes to descriptor fd, taking them from byte sequence
buf, starting at position pos in buff. Return the number of bytes actually written. write
repeats the writing operation until all bytes have been written or an error occurs.
val single_write : file_descr -> bytes -> int -> int -> int
Same as Unix.write[27.1], but attempts to write only once. Thus, if an error occurs,
single_write guarantees that no data has been written.
val write_substring : file_descr -> string -> int -> int -> int
Same as Unix.write[27.1], but take the data from a string instead of a byte sequence.
Since: 4.02.0
val single_write_substring : file_descr -> string -> int -> int -> int
Same as Unix.single_write[27.1], but take the data from a string instead of a byte
sequence.
Since: 4.02.0
Create an output channel writing on the given descriptor. The channel is initially in binary
mode; use set_binary_mode_out oc false if text mode is desired. Text mode is supported
only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: set_binary_mode_out[24.2] always fails on channels created with this
function.
Beware that output channels are buffered, so you may have to call flush[24.2] to ensure
that all data has been sent to the descriptor. Channels also keep a copy of the current
position in the file.
Closing the channel oc returned by out_channel_of_descr fd using close_out oc also
closes the underlying descriptor fd. It is incorrect to close both the channel ic and the
descriptor fd.
See Unix.in_channel_of_descr[27.1] for a discussion of the closing protocol when several
channels are created on the same descriptor.
File status
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 file’s group
st_rdev : int ;
Device ID (if special file)
st_size : int ;
Size in bytes
798
st_atime : float ;
Last access time
st_mtime : float ;
Last modification time
st_ctime : float ;
Last status change time
}
The information returned by the Unix.stat[27.1] calls.
type stats =
{ st_dev : int ;
Device number
st_ino : int ;
Chapter 27. The unix library: Unix system calls 799
Inode number
st_kind : Unix.file_kind ;
Kind of the file
st_perm : Unix.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 file’s group
st_rdev : int ;
Device ID (if special file)
st_size : int64 ;
Size in bytes
st_atime : float ;
Last access time
st_mtime : float ;
Last modification time
st_ctime : float ;
Last status change time
}
val stat : string -> stats
val lstat : string -> stats
val fstat : Unix.file_descr -> stats
end
File operations on large files. This sub-module provides 64-bit variants of the functions
Unix.LargeFile.lseek[27.1] (for positioning a file descriptor),
Unix.LargeFile.truncate[27.1] and Unix.LargeFile.ftruncate[27.1] (for changing the
size of a file), and Unix.LargeFile.stat[27.1], Unix.LargeFile.lstat[27.1] and
Unix.LargeFile.fstat[27.1] (for obtaining information on files). These alternate functions
represent positions and sizes by 64-bit integers (type int64) instead of regular integers
(type int), thus allowing operating on files whose sizes are greater than max_int.
800
Set 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, create_process and open_process functions.
It is often a security hole to leak file descriptors opened on, say, a private file to an external
program: the program, then, gets access to the private file and can do bad things with it.
Hence, it is highly recommended to set all file descriptors “close-on-exec”, except in the very
few cases where a file descriptor actually needs to be transmitted to another program.
The best way to set a file descriptor “close-on-exec” is to create it in this state. To this end,
the openfile function has O_CLOEXEC and O_KEEPEXEC flags to enforce “close-on-exec”
mode or “keep-on-exec” mode, respectively. All other operations in the Unix module that
create file descriptors have an optional argument ?cloexec:bool to indicate whether the
file descriptor should be created in “close-on-exec” mode (by writing ~cloexec:true) or in
“keep-on-exec” mode (by writing ~cloexec:false). For historical reasons, the default file
descriptor creation mode is “keep-on-exec”, if no cloexec optional argument is given. This
is not a safe default, hence it is highly recommended to pass explicit cloexec arguments to
operations that create file descriptors.
The cloexec optional arguments and the O_KEEPEXEC flag were introduced in OCaml 4.05.
Earlier, the common practice was to create file descriptors in the default, “keep-on-exec”
mode, then call set_close_on_exec on those freshly-created file descriptors. This is not as
safe as creating the file descriptor in “close-on-exec” mode because, in multithreaded
programs, a window of vulnerability exists between the time when the file descriptor is
created and the time set_close_on_exec completes. If another thread spawns another
program during this window, the descriptor will leak, as it is still in the “keep-on-exec”
mode.
Regarding the atomicity guarantees given by ~cloexec:true or by the use of the
O_CLOEXEC flag: on all platforms it is guaranteed that a concurrently-executing Caml thread
cannot leak the descriptor by starting a new process. On Linux, this guarantee extends to
concurrently-executing C threads. As of Feb 2017, other operating systems lack the
necessary system calls and still expose a window of vulnerability during which a C thread
can see the newly-created file descriptor in “keep-on-exec” mode.
Directories
val mkdir : string -> file_perm -> unit
Create a directory with the given permissions (see Unix.umask[27.1]).
type dir_handle
The type of descriptors over opened directories.
val create_process_env :
string ->
string array ->
string array -> file_descr -> file_descr -> file_descr -> int
create_process_env prog args env stdin stdout stderr works as
Unix.create_process[27.1], except that the extra argument env specifies the environment
passed to the program.
val open_process_full :
string ->
string array -> in_channel * out_channel * in_channel
Similar to Unix.open_process[27.1], but the second argument specifies the environment
passed to the command. The result is a triple of channels connected respectively to the
standard output, standard input, and standard error of the command. If the command does
not need to be run through the shell, Unix.open_process_args_full[27.1] can be used
instead of Unix.open_process_full[27.1].
val open_process_args_full :
string ->
string array ->
string array -> in_channel * out_channel * in_channel
Similar to Unix.open_process_args[27.1], but the third argument specifies the
environment passed to the new process. The result is a triple of channels connected
respectively to the standard output, standard input, and standard error of the program.
Since: 4.08.0
val close_process_full :
in_channel * out_channel * in_channel ->
process_status
Close channels opened by Unix.open_process_full[27.1], wait for the associated command
to terminate, and return its termination status.
Symbolic links
val symlink : ?to_dir:bool -> string -> string -> unit
808
symlink ?to_dir src dst creates the file dst as a symbolic link to the file src. On
Windows, to_dir indicates if the symbolic link points to a directory or a file; if omitted,
symlink examines src using stat and picks appropriately, if src does not exist then false
is assumed (for this reason, it is recommended that the to_dir parameter be specified in
new code). On Unix, to_dir is ignored.
Windows symbolic links are available in Windows Vista onwards. There are some important
differences between Windows symlinks and their POSIX counterparts.
Windows symbolic links come in two flavours: directory and regular, which designate
whether the symbolic link points to a directory or a file. The type must be correct - a
directory symlink which actually points to a file cannot be selected with chdir and a file
symlink which actually points to a directory cannot be read or written (note that Cygwin’s
emulation layer ignores this distinction).
When symbolic links are created to existing targets, this distinction doesn’t matter and
symlink will automatically create the correct kind of symbolic link. The distinction matters
when a symbolic link is created to a non-existent target.
The other caveat is that by default symbolic links are a privileged operation.
Administrators will always need to be running elevated (or with UAC disabled) and by
default normal user accounts need to be granted the SeCreateSymbolicLinkPrivilege via
Local Security Policy (secpol.msc) or via Active Directory.
Unix.has_symlink[27.1] can be used to check that a process is able to create symbolic links.
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
Chapter 27. The unix library: Unix system calls 809
(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 for writing, and block if already locked
| F_TLOCK
Lock a region for writing, or fail if already locked
| F_TEST
Test a region for other process locks
| F_RLOCK
Lock a region for reading, and block if already locked
| F_TRLOCK
Lock a region for reading, or fail if already locked
Commands for Unix.lockf[27.1].
Signals
Note: installation of signal handlers is performed via the functions Sys.signal[25.50] and Sys.set_
signal[25.50].
val kill : int -> int -> unit
kill pid signal sends signal number signal to the process with id pid.
On Windows: only the Sys.sigkill[25.50] signal is emulated.
type sigprocmask_command =
| SIG_SETMASK
| SIG_BLOCK
| SIG_UNBLOCK
val sigprocmask : sigprocmask_command -> int list -> int list
sigprocmask mode sigs changes the set of blocked signals. If mode is SIG_SETMASK,
blocked signals are set to those in the list sigs. If mode is SIG_BLOCK, the signals in sigs are
added to the set of blocked signals. If mode is SIG_UNBLOCK, the signals in sigs are removed
from the set of blocked signals. sigprocmask returns the set of previously blocked signals.
When the systhreads version of the Thread module is loaded, this function redirects to
Thread.sigmask. I.e., sigprocmask only changes the mask of the current thread.
On Windows: not implemented (no inter-process signals on Windows).
Time functions
type process_times =
{ tms_utime : float ;
User time for the process
tms_stime : float ;
Chapter 27. The unix library: Unix system calls 811
type tm =
{ tm_sec : int ;
Seconds 0..60
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.
Convert a time in seconds, as returned by Unix.time[27.1], into a date and a time. Assumes
UTC (Coordinated Universal Time), also known as GMT. To perform the inverse
conversion, set the TZ environment variable to "UTC", use Unix.mktime[27.1], and then
restore the original value of TZ.
type interval_timer =
| 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
Chapter 27. The unix library: Unix system calls 813
(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.
The three kinds of interval timers.
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 setitimer :
interval_timer ->
interval_timer_status -> interval_timer_status
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 disables the timer. Setting s.it_interval to
zero causes the timer to be disabled after its next expiration.
On Windows: not implemented.
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 ;
}
Chapter 27. The unix library: Unix system calls 815
Internet addresses
type inet_addr
The abstract type of Internet addresses.
Sockets
type socket_domain =
| PF_UNIX
Unix domain
| PF_INET
Internet domain (IPv4)
| PF_INET6
Internet domain (IPv6)
The type of socket domains. Not all platforms support IPv6 sockets (type PF_INET6).
On Windows: PF_UNIX not implemented.
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. SOCK_SEQPACKET is
included for completeness, but is rarely supported by the OS, and needs system calls that
are not available in this library.
type sockaddr =
| ADDR_UNIX of string
| ADDR_INET of inet_addr * int
Chapter 27. The unix library: Unix system calls 817
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 :
?cloexec:bool ->
socket_domain -> socket_type -> int -> file_descr
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. See
Unix.set_close_on_exec[27.1] for documentation on the cloexec optional argument.
val socketpair :
?cloexec:bool ->
socket_domain ->
socket_type -> int -> file_descr * file_descr
Create a pair of unnamed sockets, connected together. See Unix.set_close_on_exec[27.1]
for documentation on the cloexec optional argument.
type shutdown_command =
| SHUTDOWN_RECEIVE
Close for receiving
| SHUTDOWN_SEND
Close for sending
| SHUTDOWN_ALL
Close both
818
type msg_flag =
| MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
The flags for Unix.recv[27.1], Unix.recvfrom[27.1], Unix.send[27.1] and
Unix.sendto[27.1].
val recv : file_descr -> bytes -> int -> int -> msg_flag list -> int
Receive data from a connected socket.
val recvfrom :
file_descr ->
bytes -> int -> int -> msg_flag list -> int * sockaddr
Receive data from an unconnected socket.
val send : file_descr -> bytes -> int -> int -> msg_flag list -> int
Send data over a connected socket.
val send_substring :
file_descr -> string -> int -> int -> msg_flag list -> int
Same as send, but take the data from a string instead of a byte sequence.
Since: 4.02.0
val sendto :
file_descr ->
bytes -> int -> int -> msg_flag list -> sockaddr -> int
Send data over an unconnected socket.
val sendto_substring :
file_descr ->
string -> int -> int -> msg_flag list -> sockaddr -> int
Same as sendto, but take the data from a string instead of a byte sequence.
Since: 4.02.0
Chapter 27. The unix library: Unix system calls 819
Socket options
type socket_bool_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
| SO_ACCEPTCONN
Report whether socket listening is enabled
| TCP_NODELAY
Control the Nagle algorithm for TCP sockets
| IPV6_ONLY
Forbid binding an IPv6 socket to an IPv4 address
| SO_REUSEPORT
Allow reuse of address and port bindings
The socket options that can be consulted with Unix.getsockopt[27.1] and modified with
Unix.setsockopt[27.1]. These options have a boolean (true/false) value.
type socket_int_option =
| SO_SNDBUF
Size of send buffer
| SO_RCVBUF
Size of received buffer
| SO_ERROR
Deprecated. Use Unix.getsockopt_error[27.1] instead.
| SO_TYPE
Report the socket type
| SO_RCVLOWAT
820
type socket_optint_option =
| SO_LINGER
Whether to linger on closed connections that have data present, and for how long (in
seconds)
The socket options that can be consulted with Unix.getsockopt_optint[27.1] and modified
with Unix.setsockopt_optint[27.1]. These options have a value of type int option, with
None meaning “disabled”.
type socket_float_option =
| SO_RCVTIMEO
Timeout for input operations
| SO_SNDTIMEO
Timeout for output operations
The socket options that can be consulted with Unix.getsockopt_float[27.1] and modified
with Unix.setsockopt_float[27.1]. These options have a floating-point value representing
a time in seconds. The value 0 means infinite timeout.
val setsockopt_optint :
file_descr -> socket_optint_option -> int option -> unit
Same as Unix.setsockopt[27.1] for a socket option whose value is an int option.
val establish_server :
(in_channel -> out_channel -> unit) -> 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 Unix.establish_server[27.1] never returns normally.
The two channels given to the function share a descriptor to a socket. The function does
not need to close the channels, since this occurs automatically when the function returns. If
the function prefers explicit closing, it should close the output channel using
close_out[24.2] and leave the input channel unclosed, for reasons explained in
Unix.in_channel_of_descr[27.1].
On Windows: not implemented (use threads).
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.
type addr_info =
{ ai_family : socket_domain ;
Socket domain
ai_socktype : socket_type ;
Socket type
ai_protocol : int ;
Socket protocol number
ai_addr : sockaddr ;
Address
ai_canonname : string ;
Canonical host name
}
Address information returned by Unix.getaddrinfo[27.1].
type getaddrinfo_option =
| AI_FAMILY of socket_domain
Impose the given socket domain
| AI_SOCKTYPE of socket_type
Impose the given socket type
| AI_PROTOCOL of int
Impose the given protocol
| AI_NUMERICHOST
Do not call name resolver, expect numeric IP address
| AI_CANONNAME
Fill the ai_canonname field of the result
| AI_PASSIVE
Set address to “any” address for use with Unix.bind[27.1]
Options to Unix.getaddrinfo[27.1].
val getaddrinfo :
string -> string -> getaddrinfo_option list -> addr_info list
getaddrinfo host service opts returns a list of Unix.addr_info[27.1] records describing
socket parameters and addresses suitable for communicating with the given host and
service. The empty list is returned if the host or service names are unknown, or the
constraints expressed in opts cannot be satisfied.
824
host is either a host name or the string representation of an IP address. host can be given
as the empty string; in this case, the “any” address or the “loopback” address are used,
depending whether opts contains AI_PASSIVE. service is either a service name or the
string representation of a port number. service can be given as the empty string; in this
case, the port field of the returned addresses is set to 0. opts is a possibly empty list of
options that allows the caller to force a particular socket domain (e.g. IPv6 only or IPv4
only) or a particular socket type (e.g. TCP only or UDP only).
type name_info =
{ ni_hostname : string ;
Name or IP address of host
ni_service : string ;
Name of service or port number
}
Host and service information returned by Unix.getnameinfo[27.1].
type getnameinfo_option =
| NI_NOFQDN
Do not qualify local host names
| NI_NUMERICHOST
Always return host as IP address
| NI_NAMEREQD
Fail if host name cannot be determined
| NI_NUMERICSERV
Always return service as port number
| NI_DGRAM
Consider the service as UDP-based instead of the default TCP
Options to Unix.getnameinfo[27.1].
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 =
{ mutable c_ignbrk : bool ;
Chapter 27. The unix library: Unix system calls 825
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.
On Windows: not implemented.
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.
On Windows: not implemented.
828
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.
On Windows: not implemented.
Windows:
The Cygwin port of OCaml fully implements all functions from the Unix module. The native
Win32 ports implement a subset of them. Below is a list of the functions that are not
implemented, or only partially implemented, by the Win32 ports. Functions not mentioned
are fully implemented and behave as described previously in this chapter.
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 implemented (since 4.10.0)
link implemented (since 3.02)
fchmod not implemented
chown, fchown not implemented (make no sense on a DOS file
system)
umask not implemented
access execute permission X_OK cannot be tested, it just
tests for read permission instead
chroot not implemented
mkfifo not implemented
symlink, readlink implemented (since 4.03.0)
kill partially implemented (since 4.00.0): only the
sigkill signal is implemented
sigprocmask, sigpending, sigsuspend not implemented (no inter-process signals on
Windows
pause not implemented (no inter-process signals in
Windows)
alarm not implemented
times partially implemented, will not report timings
for child processes
getitimer, setitimer not implemented
getuid, geteuid, getgid, getegid always return 1
setuid, setgid, setgroups, initgroups not implemented
getgroups always returns [|1|] (since 2.00)
getpwnam, getpwuid always raise Not_found
getgrnam, getgrgid always raise Not_found
type socket_domain PF_INET is fully supported; PF_INET6 is fully
supported (since 4.01.0); PF_UNIX is not sup-
ported
establish_server not implemented; use threads
terminal functions (tc*) not implemented
setsid not implemented
830
Chapter 28
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.
Programs that use the str library must be linked as follows:
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type
#load "str.cma";;.
Regular expressions
type regexp
The type of compiled regular expressions.
831
832
Note: the argument to regexp is usually a string literal. In this case, any backslash
character in the regular expression must be doubled to make it past the OCaml string
parser. For example, the following expression:
let r = Str.regexp "hello \\([A-Za-z]+\\)" in
Str.replace_first r "\\1" "hello world"
returns the string "world".
In particular, if you want a regular expression that matches a single backslash character,
you need to quote it in the argument to regexp (according to the last item of the list above)
by adding a second backslash. Then you need to quote both backslashes (according to the
syntax of string constants in OCaml) by doubling them again, so you need to write four
backslash characters: Str.regexp "\\\\".
• Str.string_match[28.1]
• Str.search_forward[28.1]
• Str.search_backward[28.1]
• Str.string_partial_match[28.1]
• Str.global_substitute[28.1]
• Str.substitute_first[28.1]
• Str.global_replace[28.1]
• Str.replace_first[28.1]
• Str.split[28.1]
• Str.bounded_split[28.1]
• Str.split_delim[28.1]
• Str.bounded_split_delim[28.1]
834
• Str.full_split[28.1]
• Str.bounded_full_split[28.1]
• Not_found if the nth group of the regular expression was not matched.
• Invalid_argument if there are fewer than n groups in the regular expression.
• Not_found if the nth group of the regular expression was not matched.
• Invalid_argument if there are fewer than n groups in the regular expression.
Replacement
val global_replace : regexp -> string -> string -> string
global_replace regexp templ s returns a string identical to s, except that all substrings
of s that match regexp have been replaced by templ. The replacement template templ 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 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 Str.global_substitute[28.1], except that only the first substring matching the
regular expression is replaced.
Splitting
val split : regexp -> string -> string list
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. An occurrence of the delimiter at the beginning or at the end of the
string is ignored.
val bounded_split : regexp -> string -> int -> string list
836
Same as Str.split[28.1], but splits into at most n substrings, where n is the extra integer
parameter.
val bounded_split_delim : regexp -> string -> int -> string list
Same as Str.bounded_split[28.1], but occurrences of the delimiter at the beginning and at
the end of the string are recognized and returned as empty strings in the result.
type split_result =
| Text of string
| Delim of string
val full_split : regexp -> string -> split_result list
Same as Str.split_delim[28.1], but returns the delimiters as well as the substrings
contained between delimiters. The former are tagged Delim in the result list; the latter are
tagged Text. For instance, full_split (regexp "[{}]") "{ab}" returns [Delim "{";
Text "ab"; Delim "}"].
val bounded_full_split : regexp -> string -> int -> split_result list
Same as Str.bounded_split_delim[28.1], but returns the delimiters as well as the
substrings contained between delimiters. The former are tagged Delim in the result list; the
latter are tagged Text.
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).
The threads library allows concurrent programming in OCaml. 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 receiv-
ing data on communication channels.
The threads library is implemented on top of the threading facilities provided by the operating
system: POSIX 1003.1c threads for Linux, MacOS, and other Unix-like systems; Win32 threads
for Windows. Only one thread at a time is allowed to run OCaml code, hence opportunities for
parallelism are limited to the parts of the program that run system or C library code. However,
threads provide concurrency and can be used to structure programs as several communicating
processes. Threads also efficiently support concurrent, overlapping I/O operations.
Programs that use threads must be linked as follows:
Compilation units that use the threads library must also be compiled with the -I +threads
option (see chapter 11).
type t
The type of thread handles.
837
838
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.
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.
This function does nothing in the current implementation of the threading library and can
be removed from all user programs.
val select :
Unix.file_descr list ->
Unix.file_descr list ->
Unix.file_descr list ->
float -> Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
Same function as Unix.select[27.1]. Suspend the execution of the calling thread until
input/output becomes possible on the given Unix file descriptors. The arguments and
results have the same meaning as for Unix.select[27.1].
Management of signals
Signal handling follows the POSIX thread model: signals generated by a thread are delivered to
that thread; signals generated externally are delivered to one of the threads that does not block it.
Each thread possesses a set of blocked signals, which can be modified using Thread.sigmask[29.1].
This set is inherited at thread creation time. Per-thread signal masks are supported only by the
system thread library under Unix, but not under Win32, nor by the VM thread library.
val sigmask : Unix.sigprocmask_command -> int list -> int list
sigmask cmd sigs changes the set of blocked signals for the calling thread. If cmd is
SIG_SETMASK, blocked signals are set to those in the list sigs. If cmd is SIG_BLOCK, the
signals in sigs are added to the set of blocked signals. If cmd is SIG_UNBLOCK, the signals in
sigs are removed from the set of blocked signals. sigmask returns the set of previously
blocked signals for the thread.
wait_signal sigs suspends the execution of the calling thread until the process receives
one of the signals specified in the list sigs. It then returns the number of the signal
received. Signal handlers attached to the signals in sigs will not be invoked. The signals
sigs are expected to be blocked before calling wait_signal.
Mutex.lock m;
(* Critical section that operates over D *);
Mutex.unlock m
type t
The type of mutexes.
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 satisfied *) then Condition.signal c;
Mutex.unlock m
type t
The type of condition variables.
Counting semaphores
A counting semaphore is a counter that can be accessed concurrently by several threads. The
typical use is to synchronize producers and consumers of a resource by counting how many units
of the resource are available.
The two basic operations on semaphores are:
• "release" (also called "V", "post", "up", and "signal"), which increments the value of the counter.
This corresponds to producing one more unit of the shared resource and making it available
to others.
• "acquire" (also called "P", "wait", "down", and "pend"), which waits until the counter is greater
than zero and decrements it. This corresponds to consuming one unit of the shared resource.
module Counting :
sig
type t
The type of counting semaphores.
end
Chapter 29. The threads library 843
Binary semaphores
Binary semaphores are a variant of counting semaphores where semaphores can only take two
values, 0 and 1.
A binary semaphore can be used to control access to a single shared resource, with value 1
meaning "resource is available" and value 0 meaning "resource is unavailable".
The "release" operation of a binary semaphore sets its value to 1, and "acquire" waits until the
value is 1 and sets it to 0.
A binary semaphore can be used instead of a mutex (see module Mutex[29.2]) when the mutex
discipline (of unlocking the mutex from the thread that locked it) is too restrictive. The "acquire"
operation corresponds to locking the mutex, and the "release" operation to unlocking it, but "release"
can be performed in a thread different than the one that performed the "acquire". Likewise, it is
safe to release a binary semaphore that is already available.
module Binary :
sig
type t
The type of binary semaphores.
end
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 wrap_abort : 'a event -> (unit -> unit) -> 'a event
wrap_abort ev fn returns the event that performs the same communications as ev, but if
it is not selected the function fn is called after the synchronization.
The dynlink library supports type-safe dynamic loading and linking of bytecode object files (.cmo
and .cma files) in a running bytecode program, or of native plugins (usually .cmxs files) in a
running native program. Type safety is ensured by limiting the set of modules from the running
program that the loaded object file can access, and checking that the running program and the
loaded object file have been compiled against the same interfaces for these modules. In native code,
there are also some compatibility checks on the implementations (to avoid errors with cross-module
optimizations); it might be useful to hide .cmx files when building native plugins so that they
remain independent of the implementation of modules in the main program.
Programs that use the dynlink library simply need to link dynlink.cma or dynlink.cmxa with
their object files and other libraries.
Note: in order to insure that the dynamically-loaded modules have access to all the libraries
that are visible to the main program (and not just to the parts of those libraries that are actually
used in the main program), programs using the dynlink library should be linked with -linkall.
847
848
All toplevel expressions in the loaded compilation units are evaluated. No facilities are
provided to access value names defined by the unit. Therefore, the unit must itself register
its entry points with the main program (or a previously-loaded library) e.g. by modifying
tables of functions.
An exception will be raised if the given library defines toplevel modules whose names clash
with modules existing either in the main program or a shared library previously loaded with
loadfile. Modules from shared libraries previously loaded with loadfile_private are not
included in this restriction.
The compilation units loaded by this function are added to the "allowed units" list (see
Dynlink.set_allowed_units[30.1]).
Access control
val set_allowed_units : string list -> unit
Set the list of compilation units that may be referenced from units that are dynamically
loaded in the future to be exactly the given value.
Initially all compilation units composing the program currently running are available for
reference from dynamically-linked units. set_allowed_units can be used to restrict access
to a subset of these units, e.g. to the units that compose the API for dynamically-linked
code, and prevent access to all other units, e.g. private, internal modules of the running
program.
Note that Dynlink.loadfile[30.1] changes the allowed-units list.
Chapter 30. The dynlink library: dynamic loading and linking of object files 849
Error reporting
type linking_error = private
| Undefined_global of string
| Unavailable_primitive of string
| Uninitialized_global of string
type error = private
| Not_a_bytecode_file of string
| Inconsistent_import of string
| Unavailable_unit of string
| Unsafe_file
| Linking_error of string * linking_error
| Corrupted_interface of string
| Cannot_open_dynamic_library of exn
| Library's_module_initializers_failed of exn
850
| Inconsistent_implementation of string
| Module_already_loaded of string
| Private_library_cannot_implement_interface of string
exception Error of error
Errors in dynamic linking are reported by raising the Error exception with a description of
the error. A common case is the dynamic library not being found on the system: this is
reported via Cannot_open_dynamic_library (the enclosed exception may be
platform-specific).
This chapter describes three libraries which were formerly part of the OCaml distribution (Graphics,
Num, and LablTk), and a library which has now become part of OCaml’s standard library, and is
documented there (Bigarray).
Before OCaml 4.09, this package simply ensures that the graphics library was installed by the
compiler, and starting from OCaml 4.09 this package effectively provides the graphics library.
851
852
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type
#load "bigarray.cma";;.
Indexes
853
INDEX TO THE LIBRARY 855
562, 620, 624, 628, 636, 644, 650, 652, create_alarm, 604
671, 673, 678, 679, 686, 688, 706, 719, create_float, 474, 480
720, 730, 740, 756 create_matrix, 475, 480
compare_and_set, 485 create_process, 805
compare_length_with, 634, 642 create_process_env, 805
compare_lengths, 634, 642 curr, 767
Complex, 463, 539 current, 473
complex32, 489 current_dir_name, 551
complex32_elt, 488 cygwin, 749
complex64, 489
complex64_elt, 488 data, 758
concat, 475, 481, 515, 527, 552, 564, 568, 635, data_size, 659
643, 718, 730, 739 decr, 460, 486
concat_map, 637, 645, 718 default_alert_reporter, 770
Condition, 841 default_mapper, 763
conj, 539 default_report_printer, 769
connect, 817 default_uncaught_exception_handler,
cons, 634, 642, 717 693
const, 597 default_warning_reporter, 770
constant, 765, 774 delay, 838
constr_ident, 773 delete_alarm, 605
constructor_arguments, 778 deprecated, 771
constructor_declaration, 778 descr_of_in_channel, 796
container, 550 descr_of_out_channel, 796
contains, 517, 529, 731, 740 diff, 679, 720
contains_from, 517, 529, 731, 740 Digest, 463, 540
contents, 508 dim, 497
control, 601 dim1, 500, 503
convert_raw_backtrace_slot, 696 dim2, 500, 503
copy, 475, 481, 514, 526, 564, 568, 609, 614, dim3, 503
616, 660, 666, 668, 687, 702, 704, 725, dims, 492
735, 744 dir_handle, 804
copy_sign, 561 dir_sep, 551
copysign, 448 direction_flag, 766
core_type, 773, 774, 784 directive_argument, 784
core_type_desc, 775 directive_argument_desc, 784
cos, 446, 559 dirname, 553
cosh, 447, 560 disjoint, 679, 720
count, 728, 759 div, 539, 556, 618, 621, 625, 684
counters, 601 Division_by_zero, 439
Counting, 842 Division_by_zero, 437
create, 474, 480, 491, 495, 497, 499, 502, 508, doc, 471
513, 526, 545, 547, 549, 551, 563, 568, domain_of_sockaddr, 817
608, 614, 616, 660, 666, 668, 701, 725, dprintf, 594
735, 744, 757, 758, 837, 840, 841 drop_ppx_context_sig, 765
INDEX TO THE LIBRARY 859
length, 474, 479, 509, 513, 525, 563, 567, 611, major, 602
614, 616, 634, 642, 662, 666, 668, 702, major_slice, 602
725, 730, 739, 757 Make, 546, 548, 550, 615, 656, 667, 677, 683,
letop, 777 724, 754, 760
lexbuf, 631 make, 474, 480, 485, 513, 526, 563, 568, 704,
lexeme, 633 729, 738, 842, 843
lexeme_char, 633 make_float, 475, 480
lexeme_end, 633 make_formatter, 589
lexeme_end_p, 633 make_lexer, 608
lexeme_start, 633 make_matrix, 475, 480
lexeme_start_p, 633 make_self_init, 704
Lexing, 464, 631 make_symbolic_output_buffer, 590
link, 801 MakeSeeded, 546, 548, 550, 617, 669
linking_error, 849 Map, 464, 650, 670
List, 464, 634, 726 map, 476, 482, 515, 527, 542, 565, 569, 629,
list, 436 636, 644, 655, 676, 679, 688, 706, 718,
listen, 817 721, 732, 741
ListLabels, 464, 642 map_error, 706
lnot, 445 map_file, 800
loadfile, 847 map_from_array, 567, 572
loadfile_private, 848 map_left, 542
loc, 766, 767 map_opt, 764
localtime, 812 map_right, 542
Location, 766 map_to_array, 567, 571
location, 694, 695 map_val, 630
location_stack, 774 map2, 477, 482, 565, 570, 637, 645
lock, 840 mapi, 476, 482, 515, 528, 565, 569, 636, 644,
lock_command, 809 655, 676, 732, 741
lockf, 809 mapper, 763
log, 446, 540, 559 Marshal, 464, 656
log10, 446, 559 match_beginning, 834
log1p, 446, 559 match_end, 834
log2, 559 Match_failure, 438
logand, 619, 622, 626, 685 matched_group, 834
lognot, 619, 622, 626, 685 matched_string, 833
logor, 619, 622, 626, 685 Match_failure, 147, 150, 153, 437
logxor, 619, 622, 626, 685 max, 441, 562, 620, 624, 628, 687, 755
Longident, 772 max_array_length, 750
longident, 773, 784 max_binding, 654, 674
lowercase, 518, 530, 538, 735, 745 max_binding_opt, 654, 674
lowercase_ascii, 518, 530, 538, 733, 742 max_elt, 681, 722
lseek, 796, 798 max_elt_opt, 681, 722
lstat, 798, 799 max_float, 449, 557
max_floatarray_length, 750
main_program_units, 849 max_int, 444, 619, 622, 626, 684
INDEX TO THE LIBRARY 865
of_seq, 479, 485, 511, 522, 534, 567, 571, 612, out_channel_length, 456, 459
615, 617, 642, 650, 656, 664, 667, 669, out_channel_of_descr, 795
677, 682, 702, 724, 726, 735, 744 Out_of_memory, 439
of_string, 514, 526, 558, 623, 627, 686, 727 Out_of_memory, 437
of_string_opt, 558, 623, 627, 686 output, 456, 541
of_value, 496 output_binary_int, 456
ok, 705 output_buffer, 509
one, 539, 555, 618, 621, 624, 683 output_byte, 456
Oo, 464, 687 output_bytes, 455
opaque_identity, 754 output_char, 455
open_box, 574 output_string, 455
open_connection, 821 output_substring, 456
open_declaration, 782 output_value, 456
open_description, 782 over_max_boxes, 581
open_flag, 455, 794 override_flag, 766
open_hbox, 574
open_hovbox, 575 package_type, 775
open_hvbox, 574 parent_dir_name, 551
open_in, 457, 709 Parse, 772
open_in_bin, 457, 709 parse, 471, 772
open_in_gen, 457 parse_and_expand_argv_dynamic, 472
open_infos, 782 parse_argv, 472
open_out, 455 parse_argv_dynamic, 472
open_out_bin, 455 parse_dynamic, 472
open_out_gen, 455 Parse_error, 690
open_process, 805 parse_expand, 472
open_process_args, 806 Parsetree, 774
open_process_args_full, 806 Parsing, 464, 689
open_process_args_in, 806 partition, 639, 647, 653, 674, 680, 722
open_process_args_out, 806 partition_map, 639, 647
open_process_full, 806 passwd_entry, 814
open_process_in, 805 pattern, 773, 775, 784
open_process_out, 805 pattern_desc, 776
open_stag, 584 pause, 810
open_tag, 596 payload, 774
open_tbox, 581 peek, 701, 728
open_temp_file, 553 peek_opt, 701
open_vbox, 574 Pervasives, 464
opendir, 804 pi, 557
openfile, 794 pipe, 804
Option, 464, 687 polar, 540
option, 436 poll, 844
OrderedType, 650, 671, 678, 719 pop, 701, 725
os_type, 749 pop_opt, 725
out_channel, 452 pos_in, 459
INDEX TO THE LIBRARY 867
replace_first, 835 S, 544, 614, 651, 666, 671, 678, 719, 758
replace_matched, 835 safe_set_geometry, 580
replace_seq, 612, 615, 616, 664, 667, 669 Scan_failure, 711
report, 768 scanbuf, 708
report_alert, 770 Scanf, 465, 707
report_exception, 772 scanf, 715
report_kind, 768 scanner, 710
report_printer, 769 Scanning, 708
report_warning, 770 search_backward, 833
repr, 754 search_forward, 833
reset, 509, 609, 614, 616, 660, 666, 668, 768 seeded_hash, 617, 669
reshape, 506 seeded_hash_param, 618, 670
reshape_0, 506 SeededHashedType, 615, 667
reshape_1, 506 SeededS, 544, 616, 668
reshape_2, 506 seek_command, 796
reshape_3, 506 seek_in, 458, 459
Result, 465, 705 seek_out, 456, 459
result, 460 select, 808, 839, 844
return, 717 self, 838
rev, 635, 643 self_init, 703
rev_append, 635, 643 Semaphore, 841
rev_map, 636, 644 send, 818, 844
rev_map2, 637, 645 send_substring, 818
rewinddir, 804 sendto, 818
rewrite_absolute_path, 768 sendto_substring, 818
rhs_end, 689 Seq, 465, 717
rhs_end_pos, 689 service_entry, 822
rhs_interval, 767 Set, 465, 677, 719
rhs_loc, 767 set, 474, 480, 485, 493, 496, 498, 500, 503,
rhs_start, 689 513, 525, 563, 568, 602, 735, 744, 757
rhs_start_pos, 689 set_all_formatter_output_functions,
right, 542 595
rindex, 516, 528, 734, 743 set_allowed_units, 848
rindex_from, 517, 529, 734, 743 set_binary_mode_in, 459
rindex_from_opt, 517, 529, 734, 743 set_binary_mode_out, 457
rindex_opt, 516, 529, 734, 743 set_close_on_exec, 802
rmdir, 748, 803 set_cookie, 765
round, 561 set_data, 546, 548, 549
row_field, 775 set_ellipsis_text, 582
row_field_desc, 775 set_filename, 632
run_main, 764 set_formatter_out_channel, 585
runtime_parameters, 750 set_formatter_out_functions, 586
runtime_variant, 750 set_formatter_output_functions, 585
runtime_warnings_enabled, 753 set_formatter_stag_functions, 587
set_formatter_tag_functions, 596
870
Index of keywords
and, 143, 165, 170, 174, 175, 180, 186, 191 mutable, 165, 167, 168, 170, 173
as, 132, 133, 136, 137, 170, 172
asr, 130, 144, 158 new, 143, 159
assert, 163 nonrec, 165
if, 143, 144, 152 val, 168, 170, 173, 175, 177, 191
in, see let virtual, see val, method, class
include, 175, 179, 180, 182, 194
inherit, 168, 170, 172 when, 143, 149, 201
initializer, 170, 174 while, 153
with, 143, 175, 179, 191, 194
land, 130, 144, 158
lazy, 141, 143, 164
let, 143, 144, 150, 164, 170, 180, 181
lor, 130, 144, 158
lsl, 130, 144, 158
lsr, 130, 144, 158
lxor, 130, 144, 158