Ocaml Manual
Ocaml Manual
release 0.74
Documentation and user's manual
Xavier Leroy
December 2, 1997
Copyright
c 1997 Institut National de Recherche en Informatique et Automatique
2
Contents
I Getting started 7
1 Installation instructions 9
1.1 The Unix version : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 9
1.2 The Macintosh version : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 9
1.3 The MS-Windows version : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 10
1
2
III The Caml Light commands 43
4 Batch compilation (camlc) 45
4.1 Overview of the compiler : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 45
4.2 Options : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 46
4.3 Modules and the le system : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 49
4.4 Common errors : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 49
5 The toplevel system (camllight) 53
5.1 Options : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 54
5.2 Toplevel control functions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 55
5.3 The toplevel and the module system : : : : : : : : : : : : : : : : : : : : : : : : : : 58
5.4 Common errors : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 59
5.5 Building custom toplevel systems: camlmktop : : : : : : : : : : : : : : : : : : : : : 60
5.6 Options : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 61
6 The runtime system (camlrun) 63
6.1 Overview : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 63
6.2 Options : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 64
6.3 Common errors : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 64
7 The librarian (camllibr) 67
7.1 Overview : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 67
7.2 Options : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 68
7.3 Turning code into a library : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 68
8 Lexer and parser generators (camllex, camlyacc) 71
8.1 Overview of camllex : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 71
8.2 Syntax of lexer denitions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 72
8.3 Overview of camlyacc : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 74
8.4 Syntax of grammar denitions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 74
8.5 Options : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 76
8.6 A complete example : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 76
9 The debugger (camldebug) 79
9.1 Compiling for debugging : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 79
9.2 Invocation : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 79
9.3 Commands : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 80
9.4 Executing a program : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 81
9.5 Breakpoints : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 84
9.6 The call stack : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 84
9.7 Examining variable values : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 85
9.8 Controlling the debugger : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 86
9.9 Miscellaneous commands : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 89
3
10 Proling (camlpro) 91
10.1 Compiling for proling : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 91
10.2 Proling an execution : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 92
10.3 Printing proling information : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 92
10.4 Known bugs : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 92
11 Using Caml Light under Emacs 95
11.1 Updating your .emacs : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 95
11.2 The caml editing mode : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 95
11.3 Running the toplevel as an inferior process : : : : : : : : : : : : : : : : : : : : : : : 96
11.4 Running the debugger as an inferior process : : : : : : : : : : : : : : : : : : : : : : 97
12 Interfacing C with Caml Light 99
12.1 Overview and compilation information : : : : : : : : : : : : : : : : : : : : : : : : : 99
12.2 The value type : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 101
12.3 Representation of Caml Light data types : : : : : : : : : : : : : : : : : : : : : : : : 102
12.4 Operations on values : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 103
12.5 Living in harmony with the garbage collector : : : : : : : : : : : : : : : : : : : : : 105
12.6 A complete example : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 107
V Appendix 201
19 Further reading 203
19.1 Programming in ML : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 203
19.2 Descriptions of ML dialects : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 204
19.3 Implementing functional programming languages : : : : : : : : : : : : : : : : : : : 205
19.4 Applications of ML : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 206
Index to the library 207
Index of keywords 216
Foreword
This manual documents the release 0.74 of the Caml Light system. It is organized as follows.
Part I, \Getting started", explains how to install Caml Light on your machine.
Part II, \The Caml Light language reference manual", is the reference description of the Caml
Light language.
Part III, \The Caml Light commands", documents the Caml Light compiler, toplevel system,
and programming utilities.
Part IV, \The Caml Light library", describes the modules provided in the standard library.
Part V, \Appendix", contains a short bibliography, an index of all identiers dened in the
standard library, and an index of Caml Light keywords.
Conventions
The Caml Light system comes in several versions: for Unix machines, for Macintoshes, and for
PCs. The parts of this manual that are specic to one version are presented as shown below:
Unix: This is material specic to the Unix version.
Mac: This is material specic to the Macintosh version.
PC: This is material specic to the PC version.
License
The Caml Light system is copyright
c 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 Institut
National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership
rights to the Caml Light system. See the le COPYRIGHT in the distribution for the copyright notice.
The Caml Light system can be freely redistributed. More precisely, INRIA grants any user of
the Caml Light system the right to reproduce it, provided that the copies are distributed under the
conditions given in the COPYRIGHT le. The present documentation is distributed under the same
conditions.
5
6 Foreword
Availability by FTP
The complete Caml Light distribution resides on the machine ftp.inria.fr. The distribution les
can be transferred by anonymous FTP:
Host: ftp.inria.fr (Internet address 192.93.2.54)
Login name: anonymous
Password: your e-mail address
Directory: lang/caml-light
Files: see the index in le README
Part I
Getting started
7
Chapter 1
Installation instructions
This chapter explains how to install Caml Light on your machine.
This extracts the source les in the current directory. The le INSTALL contains complete instruc-
tions on how to congure, compile and install Caml Light. Read it and follow the instructions.
Troubleshooting. See the le INSTALL.
1.2 The Macintosh version
Requirements. Any Macintosh with at least 1M of RAM (2M is recommended), running System
6 or 7. About 850K of free space on the disk. The parts of the Caml Light system that support
batch compilation currently require the Macintosh Programmer's Workshop (MPW) version 3.2.
MPW is Apple's development environment, and it is distributed by APDA, Apple's Programmers
and Developers Association. See the le READ ME in the distribution for APDA's address.
Installation. Create the folder where the Caml Light les will reside. Double-click on the le
cl74macbin.sea from the distribution. This displays a le dialog box. Open the folder where the
Caml Light les will reside, and click on the Extract button. This will re-create all les from the
distribution in the Caml Light folder.
To test the installation, double-click on the application Caml Light. The \Caml Light output"
window should display something like
9
10
> Caml Light version 0.74
In the \Caml Light input" window, enter 1+2;; and press the Return key. The \Caml Light
output" window should display:
> Caml Light version 0.74
#1+2;;
- : int = 3
#
In either case, you now have to edit the camlc script, and replace the string
Macintosh HD:Caml Light:lib:
(in the rst line) with the actual pathname of the lib folder. For example, if you put Caml Light
in folder Caml Light on the disk named My HD, the rst line of camlc should read:
Set stdlib "My HD:Caml Light:lib:"
11
Chapter 2
13
14
2.1 Lexical conventions
Blanks
The following characters are considered as blanks: space, newline, horizontal tabulation, carriage
return, line feed and form feed. Blanks are ignored, but they separate adjacent identiers, literals
and keywords that would otherwise be confused as one single identier, literal or keyword.
Comments
Comments are introduced by the two characters (*, with no intervening blanks, and terminated
by the characters *), with no intervening blanks. Comments are treated as blank characters.
Comments do not occur inside string or character literals. Nested comments are correctly handled.
Identiers
ident ::= letter fletter j 0 : : : 9 j _g
letter ::= A : : : Z j a : : : z
Identiers are sequences of letters, digits and _ (the underscore character), starting with a letter.
Letters contain at least the 52 lowercase and uppercase letters from the ASCII set. Implementations
can recognize as letters other characters from the extended ASCII set. Identiers cannot contain
two adjacent underscore characters (__). Implementation may limit the number of characters of an
identier, but this limit must be above 256 characters. All characters in an identier are meaningful.
Integer literals
integer-literal ::= [-] f0 : : : 9g+
j [-] (0x j 0X) f0 : : : 9 j A : : : F j a : : : fg+
j [-] (0o j 0O) f0 : : : 7g+
j [-] (0b j 0B) f0 : : : 1g+
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 prexes select a dierent radix:
Prex Radix
0x, 0X hexadecimal (radix 16)
0o, 0O octal (radix 8)
0b, 0B binary (radix 2)
(The initial 0 is the digit zero; the O for octal is the letter O.)
Floating-point literals
oat-literal ::= [-] f0 : : : 9g+ [. f0 : : : 9g] [(e j E) [+ j -] f0 : : : 9g+ ]
Floating-point decimals consist in an integer part, a decimal part and an exponent part. The
integer part is a sequence of one or more digits, optionally preceded by a minus sign. The decimal
Chapter 2. The core Caml Light language 15
part is a decimal point followed by zero, one or more digits. The exponent part is the character e
or E followed by an optional + or - sign, followed by one or more digits. The decimal part or the
exponent part can be omitted, but not both to avoid ambiguity with integer literals.
Character literals
char-literal ::= ` regular-char `
j j j j j j
` \ (\ ` n t b r) `
j ` \ (0 ::: :::
9) (0 :::
9) (0 9) `
Character literals are delimited by ` (backquote) characters. The two backquotes enclose either
one character dierent from ` and \, or one of the escape sequences below:
Sequence Character denoted
\\ backslash (\)
\` backquote (`)
\n newline (LF)
\r return (CR)
\t horizontal tabulation (TAB)
\b backspace (BS)
\ddd the character with ASCII code ddd in decimal
String literals
string-literal ::= " fstring-character g "
string-character ::= regular-char
j \ (\ j " j n j t j b j r)
j \ (0 : : : 9) (0 : : : 9) (0 : : : 9)
String literals are delimited by " (double quote) characters. The two double quotes enclose a
sequence of either characters dierent from " and \, or escape sequences from the table below:
Sequence Character denoted
\\ backslash (\)
\" double quote (")
\n newline (LF)
\r return (CR)
\t horizontal tabulation (TAB)
\b backspace (BS)
\ddd the character with ASCII code ddd in decimal
Implementations must support string literals up to 216 ? 1 characters in length (65535 charac-
ters).
16
Keywords
The identiers below are reserved as keywords, and cannot be employed otherwise:
and as begin do done downto
else end exception for fun function
if in let match mutable not
of or prefix rec then to
try type value where while with
Ambiguities
Lexical ambiguities are resolved according to the \longest match" rule: when a character sequence
can be decomposed into two tokens in several dierent ways, the decomposition retained is the one
with the longest rst token.
2.3 Values
This section describes the kinds of values that are manipulated by Caml Light programs.
2.3.1 Base values
Integer numbers
Integer values are integer numbers from ?230 to 230 ? 1, that is ?1073741824 to 1073741823.
Implementations may support a wider range of integer values.
Floating-point numbers
Floating-point values are numbers in
oating-point representation. Everything about
oating-point
values is implementation-dependent, including the range of representable numbers, the number of
signicant digits, and the way
oating-point results are rounded.
18
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 interpretation of character codes
between 128 and 255 is implementation-dependent.
Character strings
String values are nite sequences of characters. Implementations must support strings up to 216 ? 1
characters in length (65535 characters). Implementations may support longer strings.
2.3.2 Tuples
Tuples of values are written (v1; : : :; vn ), standing for the n-tuple of values v1 to vn . Tuples of up to
214 ? 1 elements (16383 elements) must be supported, though implementations may support tuples
with more elements.
2.3.3 Records
Record values are labeled tuples of values. The record value written flabel1 = v1 ; : : : ; labeln = vn g
associates the value vi to the record label labeli, for i = 1 : : :n. Records with up to 214 ? 1 elds
(16383 elds) must be supported, though implementations may support records with more elds.
2.3.4 Arrays
Arrays are nite, variable-sized sequences of values of the same type. Arrays of length up to 214 ? 1
(16383 elements) must be supported, though implementations may support larger arrays.
2.3.5 Variant values
Variant values are either a constant constructor, or a pair of a non-constant constructor and a
value. The former case is written cconstr; the latter case is written ncconstr(v ), where v is said to
be the argument of the non-constant constructor ncconstr.
The following constants are treated like built-in constant constructors:
Constant Constructor
false the boolean false
true the boolean true
() the \unit" value
[] the empty list
2.3.6 Functions
Functional values are mappings from values to values.
Chapter 2. The core Caml Light language 19
2.4 Type expressions
typexpr ::= ' ident
j ( typexpr )
j typexpr -> typexpr
j typexpr f* typexpr g+
j typeconstr
j typexpr typeconstr
j ( typexpr f, typexpr g ) typeconstr
The table below shows the relative precedences and associativity of operators and non-closed
type constructions. The constructions with higher precedences come rst.
Operator Associativity
Type constructor application {
* {
-> right
Type expressions denote types in denitions of data types as well as in type constraints over
patterns and expressions.
Type variables
The type expression ' ident stands for the type variable named ident. In data type denitions, type
variables are names for the data type parameters. In type constraints, they represent unspecied
types that can be instantiated by any type to satisfy the type constraint.
Parenthesized types
The type expression ( typexpr ) denotes the same type as typexpr.
Function types
The type expression typexpr 1 -> typexpr 2 denotes the type of functions mapping arguments of
type typexpr 1 to results of type 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 .
20
2.5 Constants
constant ::= integer-literal
j
oat-literal
j char-literal
j string-literal
j cconstr
The syntactic class of constants comprises literals from the four base types (integers,
oating-
point numbers, characters, character strings), and constant constructors.
2.6 Patterns
pattern ::= ident
j _
j pattern as ident
j ( pattern )
j ( pattern : typexpr )
j pattern | pattern
j constant
j ncconstr pattern
j pattern , pattern f, patterng
j { label = pattern f; label = patterng }
j []
j f g
[ pattern ; pattern ]
j pattern :: pattern
The table below shows the relative precedences and associativity of operators and non-closed
pattern constructions. The constructions with higher precedences come rst.
Operator Associativity
Constructor application {
:: right
, {
| left
as {
Patterns are templates that allow selecting data structures of a given shape, and binding iden-
tiers 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 identiers to values".
Variable patterns
A pattern that consists in an identier matches any value, binding the identier to the value. The
pattern _ also matches any value, but does not bind any identier.
Chapter 2. The core Caml Light language 21
Alias patterns
The pattern pattern1 as ident matches the same values as pattern1 . If the matching against
pattern1 is successful, the identier ident is bound to the matched value, in addition to the bindings
performed by the matching against pattern1 .
Parenthesized patterns
The pattern ( pattern1 ) matches the same values as pattern1 . A type constraint can appear in a
parenthesized patterns, as in ( pattern1 : typexpr ). This constraint forces the type of pattern1 to
be compatible with type.
\Or" patterns
The pattern pattern1 | pattern2 represents the logical \or" of the two patterns pattern1 and
pattern2. A value matches pattern1 | pattern2 either if it matches pattern1 or if it matches pattern2.
The two sub-patterns pattern1 and pattern2 must contain no identiers. Hence no bindings are
returned by matching against an \or" pattern.
Constant patterns
A pattern consisting in a constant matches the values that are equal to this constant.
Variant patterns
The pattern ncconstr pattern1 matches all variants whose constructor is equal to ncconstr, and
whose argument matches pattern1 .
The pattern pattern1 :: pattern2 matches non-empty lists whose heads match pattern1 , and
whose tails match pattern2 . This pattern behaves like prefix :: ( pattern1 , pattern2 ).
The pattern [ pattern1 ; : : : ; patternn ] matches lists of length n whose elements match
pattern1 : : : patternn , respectively. This pattern behaves like pattern1 :: : : : :: patternn :: [].
Tuple patterns
The pattern pattern1 , : : : , patternn matches n-tuples whose components match the patterns
pattern1 through patternn . That is, the pattern matches the tuple values (v 1 ; : : :; v n ) such that
patterni matches v i for i = 1; : : :; n.
Record patterns
The pattern { label 1 = pattern1 ; : : : ; label n = patternn } matches records that dene at least
the labels label 1 through label n , and such that the value associated to label i match the pattern
patterni , for i = 1; : : :; n. The record value can dene more labels than label 1 : : : label n ; the values
associated to these extra labels are not taken into account for matching.
22
2.7 Expressions
expr ::= ident
j variable
j constant
j ( expr )
j begin expr end
j ( expr : typexpr )
j expr , expr f, expr g
j ncconstr expr
j expr :: expr
j [ expr f; expr g ]
j [| expr f; expr g |]
j { label = expr f; label = expr g }
j expr expr
j prex-op expr
j expr inx-op expr
j expr . label
j expr . label <- expr
j expr .( expr )
j expr .( expr ) <- expr
j expr & expr
j expr or expr
j if expr then expr [else expr]
j while expr do expr done
j for ident = expr (to j downto) expr do expr done
j expr ; expr
j match expr with simple-matching
j fun multiple-matching
j function simple-matching
j try expr with simple-matching
j let [rec] let-binding fand let-binding g in expr
simple-matching ::= pattern -> expr f| pattern -> expr g
multiple-matching ::= pattern-list -> expr f| pattern-list -> expr g
pattern-list ::= pattern fpatterng
let-binding ::= pattern = expr
j variable pattern-list = expr
prex-op ::= - j -. j !
inx-op ::= + j - j * j / j mod j +. j -. j *. j /. j ** j @ j ^ j ! j :=
j j j j j j j j j
= <> == != < <= > >= <. <=. >. >=. j j j
The table below shows the relative precedences and associativity of operators and non-closed
constructions. The constructions with higher precedence come rst.
Chapter 2. The core Caml Light language 23
Construction or operator Associativity
! {
. .( {
function application left
constructor application {
- -. (prex) {
** right
mod left
* *. / /. left
+ +. - -. left
:: right
@^ right
comparisons (= == < etc.) left
not {
& left
or left
, {
<- := right
if {
; right
let match fun function try {
The only dierence with the let construct described above is that the bindings of variables 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 identiers that
are bound by one of the patterns pattern1 ; : : :; patternn , and expect them to have the same value
as in expr, the body of the let rec construct.
The recursive denition is guaranteed to behave as described above if the expressions expr 1
to expr n are function denitions (fun : : : or function : : :), and the patterns pattern1 : : : patternn
consist in a single variable, as in:
let rec ident1 = fun : : : and : : : and ident n = fun : : : in expr
This denes ident 1 : : : identn as mutually recursive functions local to expr. The behavior of other
forms of let rec denitions is implementation-dependent.
2.7.2 Control constructs
Sequence
The expression expr 1 ; expr 2 evaluates expr 1 rst, then expr 2 , and returns the value of expr 2 .
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.
The else expr 3 part can be omitted, in which case it defaults to else ().
26
Case expression
The expression
match expr
with pattern1 -> expr 1
| :::
| patternn -> expr n
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 rst in the match expression is selected. If none of the patterns match the value of expr,
the exception Match_failure is raised.
Boolean operators
The expression expr 1 & expr 2 evaluates to true if both expr 1 and expr 2 evaluate to true; otherwise,
it evaluates to false. The rst component, expr 1, is evaluated rst. The second component, expr 2,
is not evaluated if the rst component evaluates to false. Hence, the expression expr 1 & expr 2
behaves exactly as
if expr 1 then expr 2 else false.
The expression expr 1 or expr 2 evaluates to true if one of expr 1 and expr 2 evaluates to true;
otherwise, it evaluates to false. The rst component, expr 1 , is evaluated rst. The second
component, expr 2 , is not evaluated if the rst component evaluates to true. Hence, the expression
expr 1 or expr 2 behaves exactly as
if expr 1 then true else expr 2 .
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 ().
The expression for ident = expr 1 to expr 2 do expr 3 done rst evaluates the expressions expr 1
and expr 2 (the boundaries) into integer values n and p. Then, the loop body expr 3 is repeatedly
evaluated in an environment where the local variable named ident is successively bound to the
values n, n + 1, : : : , p ? 1, p. The loop body is never evaluated if n > p.
The expression for ident = expr 1 downto expr 2 do expr 3 done rst evaluates the expressions
expr 1 and expr 2 (the boundaries) into integer values n and p. Then, the loop body expr 3 is
repeatedly evaluated in an environment where the local variable named ident is successively bound
to the values n, n ? 1, : : : , p + 1, p. The loop body is never evaluated if n < p.
In both cases, the whole for expression evaluates to the unit value ().
Chapter 2. The core Caml Light language 27
Exception handling
The expression
try expr
with pattern1 -> expr 1
| :::
patternn -> expr n
|
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 rst 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.
2.7.3 Operations on data structures
Products
The expression expr 1 , : : : , expr n evaluates to the n-tuple of the values of expressions expr 1 to
expr n . The evaluation order for the subexpressions is not specied.
Variants
The expression ncconstr expr evaluates to the variant value whose constructor is ncconstr, and
whose argument is the value of expr.
For lists, some syntactic sugar is provided. The expression expr 1 :: expr 2 stands for the
constructor prefix :: applied to the argument ( 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 .
Records
The expression { label 1 = expr 1 ; : : : ; label n = expr n } evaluates to the record value
{ label 1 = v 1 ; : : : ; label n = v n }, where v i is the value of expr i for i = 1; : : :; n. The labels label 1
to label n must all belong to the same record types; all labels belonging to this record type must
appear exactly once in the record expression, though they can appear in any order. The order in
which expr 1 to expr n are evaluated is not specied.
The expression expr 1 . label evaluates expr 1 to a record value, and returns the value associated
to label in this record value.
The expression expr 1 . label <- expr 2 evaluates expr 1 to a record value, which is then modied
in-place by replacing the value associated to label in this record by the value of expr 2. This
operation is permitted only if label has been declared mutable in the denition of the record type.
The whole expression expr 1 . label <- expr 2 evaluates to the unit value ().
28
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 unspecied.
The expression expr 1 .( expr 2 ) is equivalent to the application vect_item expr 1 expr 2. In the
initial environment, the identier vect_item resolves to a built-in function that returns the value
of element number expr 2 in the array denoted by expr 1. The rst 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 is equivalent to vect_assign expr 1 expr 2 expr 3.
In the initial environment, the identier vect_assign resolves to a built-in function that modies
in-place the array denoted by expr 1 , replacing element number expr 2 by the value of expr 3. The
exception Invalid_argument is raised if the access is out of bounds. The built-in function returns
(). Hence, the whole expression expr 1 .( expr 2 ) <- expr 3 evaluates to the unit value ().
This behavior of the two constructs expr 1 .( expr 2 ) and expr 1 .( expr 2 ) <- expr 3 may change
if the meaning of the identiers vect_item and vect_assign is changed, either by redenition or
by modication of the list of opened modules. See the discussion below on operators.
2.7.4 Operators
The operators written infix-op in the grammar above can appear in inx position (between two
expressions). The operators written prefix-op in the grammar above can appear in prex position
(in front of an expression).
The expression prex-op expr is interpreted as the application ident expr, where ident is
the identier associated to the operator prex-op in the table below. Similarly, the expression
expr 1 inx-op expr 2 is interpreted as the application ident expr 1 expr 2, where ident is the iden-
tier associated to the operator inx-op in the table below. The identiers written ident above
are then evaluated following the rules in section 2.7.1. In the initial environment, they evaluate
to built-in functions whose behavior is described in the table. The behavior of the constructions
prex-op expr and expr 1 inx-op expr 2 may change if the meaning of the identiers associated to
prex-op or inx-op is changed, either by redenition of the identiers, or by modication of the
list of opened modules, through the #open and #close directives.
Chapter 2. The core Caml Light language 29
Operator Associated Behavior in the default environment
identier
+ prefix + Integer addition.
- (inx) prefix - Integer subtraction.
- (prex) minus Integer negation.
* prefix * Integer multiplication.
/ prefix / Integer division. Raise Division_by_zero if second argu-
ment is zero. The result is unspecied if either argument is
negative.
mod prefix mod Integer modulus. Raise Division_by_zero if second argu-
ment is zero. The result is unspecied if either argument is
negative.
+. prefix +. Floating-point addition.
-. (inx) prefix -. Floating-point subtraction.
-. (prex) minus_float Floating-point negation.
*. prefix *. Floating-point multiplication.
/. prefix /. Floating-point division. Raise Division_by_zero if second
argument is zero.
** prefix ** Floating-point exponentiation.
@ prefix @ List concatenation.
^ prefix ^ String concatenation.
! prefix ! Dereferencing (return the current contents of a reference).
:= prefix := Reference assignment (update the reference given as rst
argument with the value of the second argument).
= prefix = Structural equality test.
<> prefix <> Structural inequality test.
== prefix == Physical equality test.
!= prefix != Physical inequality test.
< prefix < Test \less than" on integers.
<= prefix <= Test \less than or equal " on integers.
> prefix > Test \greater than" on integers.
>= prefix >= Test \greater than or equal" on integers.
<. prefix <. Test \less than" on
oating-point numbers.
<=. prefix <=. Test \less than or equal " on
oating-point numbers.
>. prefix >. Test \greater than" on
oating-point numbers.
>=. prefix >=. Test \greater than or equal" on
oating-point numbers.
The behavior of the +, -, *, /, mod, +., -., *. or /. operators is unspecied if the result falls
outside of the range of representable integers or
oating-point numbers, respectively. See chapter 13
for a more precise description of the behavior of the operators above.
Exception denitions add new constructors to the built-in variant type exn of exception values.
The constructors are declared as for a denition of a variant type.
2.9 Directives
directive ::= # open string
j # close string
j # ident string
Directives control the behavior of the compiler. They apply to the remainder of the current
compilation unit.
The two directives #open and #close modify the list of opened modules, that the compiler uses
to complete unqualied identiers, as described in section 2.2. The directive #open string adds the
module whose name is given by the string constant string to the list of opened modules, in rst
position. The directive #close string removes the rst occurrence of the module whose name is
given by the string constant string from the list of opened modules.
Implementations can provide other directives, provided they follow the syntax # ident string,
where ident is the name of the directive, and the string constant string is the argument to the
directive. The behavior of these additional directives is implementation-dependent.
Language extensions
This chapter describes the language features that are implemented in Caml Light, but not described
in the Caml Light reference manual. In contrast with the fairly stable kernel language that is
described in the reference manual, the extensions presented here are still experimental, and may
be removed or changed in the future.
Stream expressions are bracketed by [< and >]. They represent the concatenation of their
components. The component ' expr represents the one-element stream whose element is the value
35
36
of expr. The component expr represents a sub-stream. For instance, if both s and t are streams
of integers, then [<'1; s; t; '2>] is a stream of integers containing the element 1, then the
elements of s, then those of t, and nally 2. The empty stream is denoted by [< >].
Unlike any other kind of expressions in the language, stream expressions are submitted to lazy
evaluation: the components are not evaluated when the stream is built, but only when they are
accessed during stream matching. The components are evaluated once, the rst time they are
accessed; the following accesses reuse the value computed the rst time.
Stream patterns, also bracketed by [< and >], describe initial segments of streams. In particular,
the stream pattern [< >] matches all streams. Stream pattern components are matched against the
corresponding elements of a stream. The component ' pattern matches the corresponding stream
element against the pattern. The component expr pattern applies the function denoted by expr to
the current stream, then matches the result of the function against pattern. Finally, the component
ident simply binds the identier to the stream being matched. (The current implementation limits
ident to appear last in a stream pattern.)
Stream matching proceeds destructively: once a component has been matched, it is discarded
from the stream (by in-place modication).
Stream matching proceeds in two steps: rst, a pattern is selected by matching the stream
against the rst components of the stream patterns; then, the following components of the selected
pattern are checked against the stream. If the following components do not match, the exception
Parse_error is raised. There is no backtracking here: stream matching commits to the pattern
selected according to the rst element. If none of the rst components of the stream patterns match,
the exception Parse_failure is raised. The Parse_failure exception causes the next alternative
to be tried, if it occurs during the matching of the rst element of a stream, before matching has
committed to one pattern.
See Functional programming using Caml Light for a more gentle introductions to streams, and
for some examples of their use in writing parsers. A more formal presentation of streams, and a
discussion of alternate semantics, can be found in Parsers in ML by Michel Mauny and Daniel de
Rauglaudre, in the proceedings of the 1992 ACM conference on Lisp and Functional Programming.
3.2 Guards
Cases of a pattern matching 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:
match expr
with pattern1 [whencond 1 ] -> expr 1
| :::
| patternn [whencond n ] -> expr n
(Same syntax for the fun, function, and try : : : with constructs.) During matching, if the value of
expr matches some pattern patterni which has a guard cond i , then the expression cond i is evaluated
(in an environment enriched by the bindings performed during matching). If cond i evaluates to
true, then expr i is evaluated and its value returned as the result of the matching, as usual. But if
cond i evaluates to false, the matching is resumed against the patterns following patterni .
Chapter 3. Language extensions 37
3.3 Range patterns
In patterns, Caml Light recognizes the form ` c ` .. ` d ` (two character constants separated
by ..) as a shorthand for the pattern
` c ` | ` c 1 ` | ` c 2 ` | : : : | ` cn ` | ` d `
where c1; c2; : : :; cn are the characters that occur between c and d in the ASCII character set. For
instance, the pattern `0`..`9` matches all characters that are digits.
and correctly binds x to the cyclic list 1::2::1::2::: : : , and y to the cyclic list
2::1::2::1::: : : Informally, the class of accepted denitions consists of those denitions
where the dened variables occur only inside function bodies or as a eld of a data structure.
Moreover, the patterns in the left-hand sides must be identiers, nothing more complex.
The expression expr where let-binding behaves exactly as let let-binding in expr, and similarly
for where rec and let rec.
This allows in-place modication of the argument part of a constructed value. Modication is
performed by a new kind of expressions, written ident <- expr, where ident is an identier bound
by pattern-matching to the argument of a mutable constructor, and expr denotes the value that
must be stored in place of that argument. Continuing the example above:
38
let x = A 1 in
begin match x with A y -> y <- 2 | _ -> () end;
x
returns the value A 2. The notation ident <- expr works also if ident is an identier bound by
pattern-matching to the value of a mutable eld in a record. For instance,
type bar = {mutable lbl : int};;
let x = {lbl = 1} in
begin match x with {lbl = y} -> y <- 2 end;
x
The tokens && and || are recognized as synonymous for & (sequential \and") and or (sequen-
tial \or"), respectively.
Chapter 3. Language extensions 39
3.9 Inx symbols
Sequences of \operator characters", such as <=> or !!, are read as a single token from the
inx-symbol or prex-symbol class:
inx-symbol ::= (= j < j > j @ j ^ j | j & j ~ j + j - j * j / j $ j %) foperator-char g
prex-symbol ::= (! j ?) foperator-char g
operator-char ::= ! j $ j % j & j * j + j - j . j / j : j ; j < j = j > j ? j @ j ^ j | j ~
Tokens from these two classes generalize the built-in inx and prex operators described in chap-
ter 2:
expr ::= : : :
j prex-symbol expr
j expr inx-symbol expr
variable ::= : : :
j prefix prex-symbol
j prefix inx-symbol
No #infix directive (section 3.10) is needed to give inx symbols their inx status. The precedences
and associativities of inx symbols in expressions are determined by their rst character(s): symbols
beginning with ** have highest precedence (exponentiation), followed by symbols beginning with
*, / or % (multiplication), then + and - (addition), then @ and ^ (concatenation), then all others
symbols (comparisons). The updated precedence table for expressions is shown below. We write
\*: : : " to mean \any inx symbol starting with *".
40
Construction or operator Associativity
!::: ?::: {
. .( .[ {
function application left
constructor application {
- -. (prex) {
**: : : right
*: : : /: : : %: : : mod left
+: : : -: : : left
:: right
@: : : ^: : : right
comparisons (= == < etc.), all other inx symbols left
not {
& && left
or || left
, {
<- := right
if {
; right
let match fun function try {
Some inx and prex symbols are predened in the default environment (see chapters 2 and 13 for
a description of their behavior). The others are initially unbound and must be bound before use,
with a let prefix inx-symbol = expr or let prefix prex-symbol = expr binding.
3.10 Directives
In addition to the standard #open and #close directives, Caml Light provides three additional
directives.
#infix " id "
Change the lexical status of the identier id: in the remainder of the compilation unit, id is
recognized as an inx operator, just like +. The notation prefix id can be used to refer to
the identier id itself. Expressions of the form expr 1 id expr 2 are parsed as the application
prefix id expr 1 expr 2. The argument to the #infix directive must be an identier, that
is, a sequence of letters, digits and underscores starting with a letter; otherwise, the #infix
declaration has no eect. Example:
#infix "union";;
let prefix union = fun x y -> ... ;;
[1,2] union [3,4];;
43
Chapter 4
executes the compiled code contained in caml.out, passing it as arguments the character strings
arg 1 to arg n . (See chapter 6 for more details.)
Unix: On most Unix systems, the le produced by the linking phase can be run directly, as in:
./caml.out arg 1 arg 2 : : : arg n
The produced le has the executable bit set, and it manages to launch the bytecode inter-
preter by itself.
PC: The output le produced by the linking phase is directly executable, provided it is given
extension .EXE. Hence, if the output le is named caml_out.exe, you can execute it with
the command
caml_out arg 1 arg 2 : : : arg n
Actually, the produced le caml_out.exe is a tiny executable le prepended to the bytecode
le. The executable simply runs the camlrun runtime system on the remainder of the le.
(As a consequence, this is not a standalone executable: it still requires camlrun.exe to
reside in one of the directories in the path.)
4.2 Options
The following command-line options are recognized by camlc.
-c Compile only. Suppress the linking phase of the compilation. Source code les are turned into
compiled les, but no executable le is produced. This option is useful to compile modules
separately.
-ccopt option
Pass the given option to the C compiler and linker, when linking in \custom runtime" mode
(see the -custom option). For instance, -ccopt -Ldir causes the C linker to search for C
libraries in directory dir.
-custom
Link in \custom runtime" mode. In the default linking mode, the linker produces bytecode
that is intended to be executed with the shared runtime system, camlrun. In the custom
runtime mode, the linker produces an output le that contains both the runtime system and
the bytecode for the program. The resulting le is considerably larger, but it can be executed
directly, even if the camlrun command is not installed. Moreover, the \custom runtime" mode
enables linking Caml Light code with user-dened C functions, as described in chapter 12.
Chapter 4. Batch compilation (camlc) 47
Unix: Never strip an executable produced with the -custom option.
PC: This option requires the DJGPP port of the GNU C compiler to be installed.
-g Cause the compiler to produce additional debugging information. During the linking phase,
this option add information at the end of the executable bytecode le produced. This infor-
mation is required by the debugger camldebug and also by the catch-all exception handler
from the standard library module printexc.
During the compilation of an implementation le (.ml le), when the -g option is set, the
compiler adds debugging information to the .zo le. It also writes a .zix le that describes
the full interface of the .ml le, that is, all types and values dened in the .ml le, including
those that are local to the .ml le (i.e. not declared in the .mli interface le). Used in
conjunction with the -g option to the toplevel system (chapter 5), the .zix le gives access
to the local values of the module, making it possible to print or \trace" them. The .zix le
is not produced if the implementation le has no explicit interface, since, in this case, the
module has no local values.
-i Cause the compiler to print the declared types, exceptions, and global variables (with their
inferred types) when compiling an implementation (.ml le). This can be useful to check
the types inferred by the compiler. Also, since the output follows the syntax of module
interfaces, it can help in writing an explicit interface (.mli le) for a le: just redirect the
standard output of the compiler to a .mli le, and edit that le to remove all declarations
of unexported globals.
-I directory
Add the given directory to the list of directories searched for compiled interface les (.zi) and
compiled object code les (.zo). By default, the current directory is searched rst, then the
standard library directory. Directories added with -I are searched after the current directory,
but before the standard library directory. When several directories are added with several -I
options on the command line, these directories are searched from right to left (the rightmost
directory is searched rst, the leftmost is searched last). (Directories can also be added to
the search path from inside the programs with the #directory directive; see chapter 3.)
-lang language-code
Translate the compiler messages to the specied language. The language-code is fr for French,
es for Spanish, de for German, : : : (See the le camlmsgs.txt in the Caml Light standard
library directory for a list of available languages.) When an unknown language is specied,
or no translation is available for a message, American English is used by default.
-o exec-le
Specify the name of the output le produced by the linker.
Unix: The default output name is a.out, in keeping with the tradition.
PC: The default output name is caml_out.exe.
Mac: The default output name is Caml.Out.
48
-O module-set
Specify which set of standard modules is to be implicitly \opened" at the beginning of a
compilation. There are three module sets currently available:
cautious
provides the standard operations on integers,
oating-point numbers, characters, strings,
arrays, : : : , as well as exception handling, basic input/output, etc. Operations from the
cautious set perform range and bound checking on string and array operations, as well
as various sanity checks on their arguments.
fast
provides the same operations as the cautious set, but without sanity checks on their
arguments. Programs compiled with -O fast are therefore slightly faster, but unsafe.
none
suppresses all automatic opening of modules. Compilation starts in an almost empty
environment. This option is not of general use, except to compile the standard library
itself.
The default compilation mode is -O cautious. See chapter 13 for a complete listing of the
modules in the cautious and fast sets.
-p Compile and link in proling mode. See the description of the proler camlpro in chapter 10.
-v Print the version number of the compiler.
-W Print extra warning messages for the following events:
A #open directive is useless (no identier in the opened module is ever referenced).
A variable name in a pattern matching is capitalized (often corresponds to a misspelled
constant constructor).
Unix: The following environment variable is also consulted:
LANG
When set, control which language is used to print the compiler messages (see the -lang
command-line option).
PC: The following option is also supported:
@response-le
Process the les whose names are listed in le response-le, just as if these names
appeared on the command line. File names in response-le are separated by blanks
(spaces, tabs, newlines). This option allows to overcome silly limitations on the length
of the command line.
The following environment variables are also consulted:
CAMLLIB
Contain the path to the standard library directory.
Chapter 4. Batch compilation (camlc) 49
LANG
When set, control which language is used to print the compiler messages (see the -lang
command-line option).
This result in the error message \expression C of type foo cannot be used with type foo".
Incompatible types with the same names can also appear when a module is changed and
recompiled, but some of its clients are not recompiled. That's because type constructors in
.zi les are not represented by their name (that would not suce to identify them, because
of type redenitions), but by unique stamps that are assigned when the type declaration is
compiled. Consider the three modules:
mod1.ml: type t = A | B;;
let f = function A -> 0 | B -> 1;;
Now, assume mod1.ml is changed and recompiled, but mod2.ml is not recompiled. The recom-
pilation of mod1.ml can change the stamp assigned to type t. But the interface mod2.zi will
still use the old stamp for mod1__t in the type of mod2__g. Hence, when compiling mod3.ml,
the system complains that the argument type of mod2__g (that is, mod1__t with the old
stamp) is not compatible with the type of mod1__A (that is, mod1__t with the new stamp).
Fix: use make or a similar tool to ensure that all clients of a module mod are recompiled when
the interface mod.zi changes. To check that the Makefile contains the right dependencies,
remove all .zi les and rebuild the whole program; if no \Cannot nd le" error appears,
you're all set.
The type inferred for name, that is, t, contains non-generalizable type variables
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
Chapter 4. Batch compilation (camlc) 51
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, identiers, 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 o.
Non-generalized type variables in a type cause no diculties inside a given compilation unit
(the contents of a .ml le, or an interactive session), but they cannot be allowed in types
written in a .zi compiled interface le, because they could be used inconsistently in other
compilation units. Therefore, the compiler
ags an error when a .ml implementation without
a .mli interface denes a global variable name whose type contains non-generalized type
variables. There are two solutions to this problem:
Add a type constraint or a .mli interface to give a monomorphic type (without type
variables) to name. For instance, instead of writing
let sort_int_list = sort (prefix <);;
(* inferred type 'a list -> 'a list, with 'a not generalized *)
write
let sort_int_list = (sort (prefix <) : int list -> int list);;
If you really need name to have a polymorphic type, turn its dening expression into a
function by adding an extra parameter. For instance, instead of writing
let map_length = map vect_length;;
(* inferred type 'a vect list -> int list, with 'a not generalized *)
write
let map_length lv = map vect_length lv;;
dene
mod1.ml: let f g x = ... g ... ;;
mod2.ml: let rec g y = ... mod1__f g ... ;;
Unavailable C primitive f
This error appears when trying to link code that calls external functions written in C in
\default runtime" mode. As explained in chapter 12, such code must be linked in \custom
runtime" mode. Fix: add the -custom option, as well as the (native code) libraries and
(native code) object les that implement the required external functions.
Chapter 5
Unix: The toplevel system is started by the command camllight. Phrases are read on standard
input, results are printed on standard output, errors on standard error. End-of-le on
standard input terminates camllight (see also the quit system function below).
The toplevel system does not perform line editing, but it can easily be used in conjunction
with an external line editor such as fep; just run fep -emacs camllight or fep -vi
camllight. Another option is to use camllight under Gnu Emacs, which gives the full
editing power of Emacs (see the directory contrib/camlmode in the distribution).
At any point, the parsing, compilation or evaluation of the current phrase can be inter-
rupted by pressing ctrl-C (or, more precisely, by sending the intr signal to the camllight
process). This goes back to the # prompt.
Mac: The toplevel system is presented as the standalone Macintosh application Caml Light. This
application does not require the Macintosh Programmer's Workshop to run.
Once launched from the Finder, the application opens two windows, \Caml Light Input"
and \Caml Light Output". Phrases are entered in the \Caml Light Input" window. The
\Caml Light Output" window displays a copy of the input phrases as they are processed by
the Caml Light toplevel, interspersed with the toplevel responses. The \Return" key sends
the contents of the Input window to the Caml Light toplevel. The \Enter" key inserts a
newline without sending the contents of the Input window. (This can be congured with
the \Preferences" menu item.)
The contents of the input window can be edited at all times, with the standard Macintosh
interface. An history of previously entered phrases is maintained, and can be accessed with
the \Previous entry" (command-P) and \Next entry" (command-N) menu items.
53
54
To quit the Caml Light application, either select \Quit" from the \Files" menu, or use the
quit function described below.
At any point, the parsing, compilation or evaluation of the current phrase can be interrupted
by pressing \command-period", or by selecting the item \Interrupt Caml Light" in the
\Caml Light" menu. This goes back to the # prompt.
PC: The toplevel system is presented as a Windows application named Camlwin.exe. It should
be launched from the Windows le manager or program manager.
The \Terminal" windows is split in two panes. Phrases are entered and edited in the
bottom pane. The top pane displays a copy of the input phrases as they are processed by
the Caml Light toplevel, interspersed with the toplevel responses. The \Return" key sends
the contents of the bottom pane to the Caml Light toplevel. The \Enter" key inserts a
newline without sending the contents of the Input window. (This can be congured with
the \Preferences" menu item.)
The contents of the input window can be edited at all times, with the standard Windows
interface. An history of previously entered phrases is maintained and displayed in a separate
window.
To quit the Camlwin application, either select \Quit" from the \File" menu, or use the quit
function described below.
At any point, the parsing, compilation or evaluation of the current phrase can be interrupted
by selecting the \Interrupt Caml Light" menu item. This goes back to the # prompt.
A text-only version of the toplevel system is available under the name caml.exe. It runs
under MSDOS as well as under Windows in a DOS window. No editing facilities are
provided.
5.1 Options
The following command-line options are recognized by the caml or camllight commands.
-g Start the toplevel system in debugging mode. This mode gives access to values and types
that are local to a module, that is, not exported by the interface of the module. When
debugging mode is o, these local objects are not accessible (attempts to access them produce
an \Unbound identier" error). When debugging mode is on, these objects become visible,
just like the objects that are exported in the module interface. In particular, values of abstract
types are printed using their concrete representations, and the functions local to a module
can be \traced" (see the trace function in section 5.2). This applies only to the modules that
have been compiled in debugging mode (either by the batch compiler with the -g option, or
by the toplevel system in debugging mode), that is, those modules that have an associated
.zix le.
-I directory
Add the given directory to the list of directories searched for compiled interface les (.zi) and
compiled object code les (.zo). By default, the current directory is searched rst, then the
standard library directory. Directories added with -I are searched after the current directory,
Chapter 5. The toplevel system (camllight) 55
but before the standard library directory. When several directories are added with several -I
options on the command line, these directories are searched from right to left (the rightmost
directory is searched rst, the leftmost is searched last). Directories can also be added to the
search path once the toplevel is running with the #directory directive; see chapter 3.
-lang language-code
Translate the toplevel messages to the specied language. The language-code is fr for French,
es for Spanish, de for German, : : : (See the le camlmsgs.txt in the Caml Light standard
library directory for a list of available languages.) When an unknown language is specied,
or no translation is available for a message, American English is used by default.
-O module-set
Specify which set of standard modules is to be implicitly \opened" when the toplevel starts.
There are three module sets currently available:
cautious
provides the standard operations on integers,
oating-point numbers, characters, strings,
arrays, : : : , as well as exception handling, basic input/output, : : : Operations from the
cautious set perform range and bound checking on string and vector operations, as well
as various sanity checks on their arguments.
fast
provides the same operations as the cautious set, but without sanity checks on their
arguments. Programs compiled with -O fast are therefore slightly faster, but unsafe.
none
suppresses all automatic opening of modules. Compilation starts in an almost empty
environment. This option is not of general use.
The default compilation mode is -O cautious. See chapter 13 for a complete listing of the
modules in the cautious and fast sets.
Unix: The following environment variables are also consulted:
LANG
When set, control which language is used to print the compiler messages (see the -lang
command-line option).
LC_CTYPE
If set to iso_8859_1, accented characters (from the ISO Latin-1 character set) in string
and character literals are printed as is; otherwise, they are printed as decimal escape
sequences (\ddd).
executing load "foo" denes the identier foo__bar with value 1. Caveat: the loaded
module is not automatically opened: the identier bar does not automatically complete to
foo__bar. To achieve this, you must execute the directive #open "foo" afterwards.
value compile : string -> unit
Compile the source code for a module implementation or interface (.ml or .mli le).
Compilation proceeds as with the batch compiler, and produces the same results as
camlc -c. If the toplevel system is in debugging mode (option -g or function debug_mode
below), the compilation is also performed in debugging mode, as when giving the -g option
to the batch compiler. The result of the compilation is left in les (.zo, .zi, .zix). The
compiled code is not loaded in memory. Use load_object to load a .zo le produced by
compile.
value load_object : string -> unit
Load in memory the compiled bytecode contained in the given le. The .zo extension is
automatically added to the le name, if not present. The bytecode le has been produced
either by the standalone compiler camlc or by the compile function. Global identiers
dened in the le being loaded are entered in their own module, not in the top module, just
as with the load function.
value trace : string -> unit
After the execution of trace "foo", all calls to the global function named foo will be
\traced". That is, the argument and the result are displayed for each call, as well as the
exceptions escaping out of foo, either raised by foo itself, or raised by one of the functions
called from foo. If foo is a curried function, each argument is printed as it is passed to the
function. Only functions implemented in ML can be traced; system primitives such as
string_length or user-supplied C functions cannot.
Chapter 5. The toplevel system (camllight) 57
value untrace : string -> unit
Executing untrace "foo" stops all tracing over the global function named foo.
value verbose_mode: bool -> unit
verbose_mode true causes the compile function to print the inferred types and other
information.
verbose_mode false reverts to the default silent behavior.
remove_printer "printername" removes the function named printername from the table
of toplevel printers.
value set_print_depth : int -> unit
Set whether extended module interfaces must be used debug_mode true or not
debug_mode false. Extended module interfaces are .zix les that describe the actual
implementation of a module, including private types and variables. They are generated
when compiling with camlc -g, or with the compile function above when debug_mode is
true. When debug_mode is true, toplevel phrases can refer to private types and variables of
modules, and private functions can be traced with trace. Setting debug_mode true is
equivalent to starting the toplevel with the -g option.
value cd : string -> unit
Add the given directory to the search path for les. Same behavior as the -I option or the
#directory directive.
58
5.3 The toplevel and the module system
Toplevel phrases can refer to identiers dened in modules other than the top module with
the same mechanisms as for separately compiled modules: either by using qualied identiers
(modulename__localname), or by using unqualied identiers that are automatically completed
by searching the list of opened modules. (See section 2.2.) The modules opened at startup are
given in the documentation for the standard library. Other modules can be opened with the #open
directive.
However, before referencing a global variable from a module other than the top module, a
denition of that global variable must have been entered in memory. At start-up, the toplevel
system contains the denitions for all the identiers in the standard library. The denitions for
user modules can be entered with the load or load_object functions described above. Referencing
a global variable for which no denition has been provided by load or load_object results in
the error \Identifier foo__bar is referenced before being defined". Since this is a tricky
point, let us consider some examples.
1. The library function sub_string is dened in module string. This module is part of the
standard library, and is one of the modules automatically opened at start-up. Hence, both
phrases
sub_string "qwerty" 1 3;;
string__sub_string "qwerty" 1 3;;
causes the error \Variable printf is unbound", since none of the currently opened mod-
ules dene a global with local name printf. However,
#open "printf";;
printf "%s %s" "hello" "world";;
executes correctly.
3. Assume the le foo.ml resides in the current directory, and contains the single phrase
let x = 1;;
Chapter 5. The toplevel system (camllight) 59
When the toplevel starts, references to x will cause the error \Variable x is unbound".
References to foo__x will cause the error \Cannot find file foo.zi", since the typechecker
is attempting to load the compiled interface for module foo in order to nd the type of x. To
load in memory the module foo, just do:
load "foo";;
Then, references to foo__x typecheck and evaluate correctly. Since load does not open the
module it loads, references to x will still fail with the error \Variable x is unbound". You
will have to do
#open "foo";;
This loads the le foo.zo in memory, therefore dening foo__x. Then, references to foo__x
evaluate correctly. As in case 3 above, references to x still fail, because load_object does
not open the module it loads. Again, you will have to do
#open "foo";;
This creates the bytecode le mytoplevel, containing the Caml Light toplevel system, plus the
code from the three .zo les. To run this toplevel, give it as argument to the camllight command:
camllight mytoplevel
This starts a regular toplevel loop, except that the code from foo.zo, bar.zo and gee.zo is already
loaded in memory, just as if you had typed:
load_object "foo";;
load_object "bar";;
load_object "gee";;
on entrance to the toplevel. The modules foo, bar and gee are not opened, though; you still have
to do
#open "foo";;
-I directory
Add the given directory to the list of directories searched for compiled object code les (.zo).
-o exec-le
Specify the name of the toplevel le produced by the linker.
Unix: The default is camltop.out.
PC: The default is camltop.exe. The name must have .exe extension.
62
Chapter 6
The rst non-option argument is taken to be the name of the le containing the executable bytecode.
(That le is searched in the executable path as well as in the current directory.) The remaining
arguments are passed to the Caml Light program, in the string array sys__command_line. Element
0 of this array is the name of the bytecode executable le; elements 1 to n are the remaining
arguments arg 1 to arg n .
As mentioned in chapter 4, in most cases, the bytecode executable les produced by the camlc
command are self-executable, and manage to launch the camlrun command on themselves auto-
matically. That is, assuming caml.out is a bytecode executable le,
caml.out arg 1 ... arg n
works exactly as
camlrun caml.out arg 1 ... arg n
Notice that it is not possible to pass options to camlrun when invoking caml.out directly.
63
64
6.2 Options
The following command-line option is recognized by camlrun.
-V Print out the camlrun version number. Exit immediately without executing any byte-code
le.
The following environment variable are also consulted:
CAMLRUNPARAM
Set the garbage collection parameters. This variable must be a sequence of parameter spec-
ications. A parameter specication is an option letter followed by an = sign and a decimal
number. There are four options, corresponding to the four elds of the control record
documented in section 14.5:
s (minor_heap_size) Size of the minor heap.
i (major_heap_increment) Minimum size increment for the major heap.
o (space_overhead) The major GC speed setting.
v (verbose) Whether to print GC messages or not. 0 is false; 1 is true; other values may
give unexpected results.
For example, under csh the command
setenv CAMLRUNPARAM 's=250000 v=1'
tells a subsequent camlrun to set its initial minor heap size to about 1 megabyte (on a 32-bit
machine) and to print its GC messages.
PATH
List of directories searched to nd the bytecode executable le.
The typical use of camllibr is to build a library composed of several modules: this way, users
of the library have only one .zo le to specify on the command line to camlc, instead of a bunch
of .zo les, one per module contained in the library.
The linking phase of camlc is clever enough to discard the code corresponding to useless phrases:
in particular, denitions for global variables that are never used after their denitions. Hence, there
is no problem with putting many modules, even rarely used ones, into one single library: this will
not result in bigger executables.
The usage for camllibr is:
camllibr options le 1 .zo ... le n .zo
where le 1 .zo through le n .zo are the object les to pack together. The order in which these le
names are presented on the command line is relevant: the compiled phrases contained in the library
will be executed in that order. (Remember that it is a link-time error to refer to a global variable
that has not yet been dened.)
67
68
7.2 Options
The following command-line options are recognized by camllibr.
-I directory
Add the given directory to the list of directories searched for the input .zo les. By default,
the current directory is searched rst, then the standard library directory. Directories added
with -I are searched after the current directory, but before the standard library directory.
When several directories are added with several -I options on the command line, these direc-
tories are searched from right to left (the rightmost directory is searched rst, the leftmost is
searched last).
-o library-name
Specify the name of the output le. The default is library.zo.
PC: The following option is also supported:
@response-le
Process the les whose names are listed in le response-le, just as if these names
appeared on the command line. File names in response-le are separated by blanks
(spaces, tabs, newlines). This option allows to overcome silly limitations on the length
of the command line.
The implementation of the mylib module simply equates the abstract types and the public functions
to the corresponding types and functions in the modules windows, images and buttons:
Chapter 7. The librarian (camllibr) 69
(* File mylib.ml *)
type window == windows__win
and image == images__pixmap
and button == buttons__t;;
let new_window = windows__open_window
and draw_image = images__draw
and ...
The les windows.ml, images.ml and buttons.ml can open the mylib module, to access the public
types dened in the interface mylib.mli, such as the option type. Of course, these modules must
not reference the abstract types nor the public functions, to avoid circularities.
Types such as windows__win in the example above can be exported by the windows module
either abstractly or concretely (with their denition). Often, it is necessary to export them con-
cretely, because the other modules in the library (images, buttons) need to build or destructure
directly values of that type. Even if windows__win is exported concretely by the windows module,
that type will remain abstract to the library user, since it is abstracted by the public interface
mylib.
The actual building of the library mylib proceeds as follows:
camlc -c mylib.mli # create mylib.zi
camlc -c windows.mli windows.ml images.mli images.ml
camlc -c buttons.mli buttons.ml
camlc -c mylib.ml # create mylib.zo
mv mylib.zo tmplib.zo # renaming to avoid overwriting mylib.zo
camllibr -o mylib.zo windows.zo images.zo buttons.zo tmplib.zo
Then, copy mylib.zi and mylib.zo to a place accessible to the library users. The other .zi and
.zoles need not be copied.
70
Chapter 8
produces Caml Light code for a lexical analyzer in le lexer.ml. This le denes one lexing func-
tion per entry point in the lexer denition. These functions have the same names as the entry
points. Lexing functions take as argument a lexer buer, and return the semantic attribute of the
corresponding entry point.
Lexer buers are an abstract data type implemented in the standard library module lexing.
The functions create_lexer_channel, create_lexer_string and create_lexer from module
71
72
lexing create lexer buers that read from an input channel, a character string, or any reading
function, respectively. (See the description of module lexing in chapter 13.)
When used in conjunction with a parser generated by camlyacc, the semantic actions compute
a value belonging to the type token dened by the generated parsing module. (See the description
of camlyacc below.)
produces Caml Light code for a parser in the le grammar.ml, and its interface in le grammar.mli.
The generated module denes 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 buers to tokens) and a lexer buer, and return the semantic
attribute of the corresponding entry point. Lexical analyzer functions are usually generated from a
lexer specication by the camllex program. Lexer buers are an abstract data type implemented
in the standard library module lexing. Tokens are values from the concrete type token, dened
in the interface le grammar.mli produced by camlyacc.
Rules can also contain the %prec symbol directive in the right-hand side part, to override the
default precedence and associativity of the rule with the precedence and associativity of the given
symbol.
Semantic actions are arbitrary Caml Light expressions, that are evaluated to produce the se-
mantic attribute attached to the dened 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 rst (leftmost) symbol, $2 is the attribute for the second symbol, etc.
Actions occurring in the middle of rules are not supported. Error recovery is not implemented.
8.5 Options
The camlyacc command recognizes the following options:
-v Generate a description of the parsing tables and a report on con
icts resulting from ambigu-
ities in the grammar. The description is put in le grammar.output.
-s Generate a grammar.ml le with smaller phrases. Semantic actions are presented in the
grammar.ml output le as one large vector of functions. By default, this vector is built by
a single phrase. When the grammar is large, or contains complicated semantic actions, the
resulting phrase may require large amounts of memory to be compiled by Caml Light. With
the -s option, the vector of actions is constructed incrementally, one phrase per action. This
lowers the memory requirements for the compiler, but it is no longer possible to infer the
types of nonterminal symbols: typechecking is turned o on symbols that do not have a type
specied by a %type directive.
-bprex
Name the output les prex.ml, prex.mli, prex.output, instead of the default naming
convention.
Here is the main program, that combines the parser with the lexer:
(* File calc.ml *)
try
let lexbuf = lexing__create_lexer_channel std_in in
while true do
78
let result = parser__Main lexer__Token lexbuf in
print_int result; print_newline(); flush std_out
done
with Eof ->
()
;;
9.2 Invocation
9.2.1 Starting the debugger
The Caml Light debugger is invoked by running the program camldebug with the name of the
bytecode executable le as argument:
camldebug program
79
80
-s socket
Use socket for communicating with the debugged program. See the description of the com-
mand set socket (section 9.8.7) for the format of socket.
-c count
Set the maximum number of checkpoints to count.
-cd directory
Run the debugger program from the working directory directory, instead of the current di-
rectory.
-emacs
Tell the debugger it is executing under Emacs. (See section 11.4 for information on how to
run the debugger under Emacs.)
9.2.2 Quitting the debugger
The command quit exits the debugger. You can also exit the debugger by typing an end-of-le
character (usually ctrl-D).
Typing an interrupt character (usually ctrl-C) will not exit the debugger, but will terminate
the action of any debugger command that is in progress and return to the debugger command level.
9.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
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.
9.3.1 Getting help
The Caml Light debugger has a simple on-line help system, which gives a brief description of each
command and variable.
help
Print the list of commands.
help command
Give help about the command command.
Chapter 9. The debugger (camldebug) 81
help set variable, help show variable
Give help about the variable variable. The list of all debugger variables can be obtained with
help set.
step 0
Load the program and stop on the rst event.
goto time
Load the program and execute it until the given time. Useful when you already know ap-
proximately at what time the problem appears. Also useful to set breakpoints on function
values that have not been computed at time 0 (see section 9.5).
The execution of a program is aected by certain information it receives when the debugger
starts it, such as the command-line arguments to the program and its working directory. The
debugger provides commands to specify this information (set arguments and cd). These com-
mands must be used before program execution starts. If you try to change the arguments or the
working directory after starting your program, the debugger will kill the program (after asking for
conrmation).
Chapter 9. The debugger (camldebug) 83
9.4.3 Running the program
The following commands execute the program forward or backward, starting at the current time.
The execution will stop either when specied by the command or when a breakpoint is encountered.
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.
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.
finish
Run the program until the current function returns.
9.4.4 Time travel
You can jump directly to a given time, without stopping on breakpoints, using the goto command.
As you move through the program, the debugger maintains an history of the successive times
you stop at. The last command can be used to revisit these times: each last command moves one
step back through the history. That is useful mainly to undo commands such as step and next.
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.
set history size
Set the size of the execution history.
9.4.5 Killing the program
kill
Kill the program being executed. This command is mainly useful if you wish to recompile
the program without leaving the debugger.
84
9.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.
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 identier function has been computed and assigned to the identier. Hence this command
cannot be used at the very beginning of the program execution, when all identiers are still
undened. Moreover, C functions are not recognized by the debugger.
break @ [module ] line
Set a breakpoint in module module (or in the current module if module is not given), at the
rst event of line line.
break @ [module ] line column
Set a breakpoint in module module (or in the current module if module is not given), at the
event closest to line line, column column.
break @ [module ] # character
Set a breakpoint in module module at the event closest to character number character.
break address
Set a breakpoint at the code address address.
delete [breakpoint-numbers ]
Delete the specied breakpoints. Without argument, all breakpoints are deleted (after asking
for conrmation).
info breakpoints
Print the list of all breakpoints.
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 all options
f function calls : a count point is set at the beginning of function bodies
i if : : : then : : : else : : : : count points are set in both then branch and else branch
l while, for loops: a count point is set at the beginning of the loop body
m match branches: a count point is set at the beginning of the body of each branch
t try : : : with : : : branches: a count point is set at the beginning of the body of each branch
For instance, compiling with -pfilm proles function calls, if: : : then : : : else: : : , loops and
pattern matching.
The -p option without additional letters defaults to -pfm, meaning that only function calls and
pattern matching are proled.
91
92
10.2 Proling an execution
Running a bytecode executable le that has been compiled and linked with -p records the execution
counts for the specied parts of the program and saves them in a le called camlpro.dump in the
current directory.
More precisely, the dump le camlpro.dump is written when the io__exit function is called.
The linker, called with the -p option, adds io__exit 0 as the last phrase of the bytecode executable,
in case the original program never calls io__exit. However, if the program terminates with an
uncaught exception, the dump le will not be produced.
If a compatible dump le already exists in the current directory, then the proling information
is accumulated in this dump le. This allows, for instance, the proling of several executions of a
program on dierent inputs.
prints the source code for the foo module, with comments indicating how many times the functions
in this module have been called. Naturally, this information is accurate only if the source le has
not been modied since the proling execution took place.
The following options are recognized by camlpro:
compiler options -stdlib, -I, -include, -O, -open, -i, -lang
See chapter 4 for the detailed usage.
-f dumple
Species an alternate dump le of proling information
-F string
Species an additional string to be output with proling information. By default, camlpro
will annotate progams with comments of the form (* n *) where n is the counter value for
a proling point. With option -F s, the annotation will be (* sn *).
An additional argument species the output le. For instance
camlpro -f ../test/camlpro.dump foo.ml foo_profiled.ml
will save the annotated program in le foo_profiled.ml. Otherwise, the annotated program is
written on the standard output.
will break the proler. More precisely, one should avoid to refer to symbols of the current module
with the qualied symbol syntax.
94
Chapter 11
C-c >
down command: select the stack frame below the current frame.
C-c <
up command: select the stack frame above the current frame.
C-c C-f
finish command: run till the current function returns.
In a buer in Caml editing mode, C-x SPC sets a breakpoint at the current position of the
point.
98
Chapter 12
Primitives with several arguments are always curried. The C function does not necessarily have
the same name as the ML function.
Values thus declared primitive in a module interface must not be implemented in the module
implementation (the .ml le). They can be used inside the module implementation.
12.1.2 Implementing primitives
User primitives with arity n 5 are implemented by C functions that take n arguments of type
value, and return a result of type value. The type value is the type of the representations
for Caml Light values. It encodes objects of several base types (integers,
oating-point numbers,
strings, : : : ), as well as Caml Light data structures. The type value and the associated conversion
functions and macros are described in details below. For instance, here is the declaration for the C
function implementing the input primitive:
value input(channel, buffer, offset, length)
value channel, buffer, offset, length;
{
...
}
99
100
When the primitive function is applied in a Caml Light program, the C function is called with
the values of the expressions to which the primitive is applied as arguments. The value returned
by the function is passed back to the Caml Light program as the result of the function application.
User primitives with arity greater than 5 are implemented by C functions that receive two
arguments: a pointer to an array of Caml Light values (the values for the arguments), and an
integer which is the number of arguments provided:
value prim_with_lots_of_args(argv, argn)
value * argv;
int argn;
{
... argv[0] ...; /* The first argument */
... argv[6] ...; /* The seventh argument */
}
Implementing a user primitive is actually two separate tasks: on the one hand, decoding the
arguments to extract C values from the given Caml Light values, and encoding the return value as
a Caml Light value; on the other hand, actually computing the result from the arguments. Except
for very simple primitives, it is often preferable to have two distinct C functions to implement
these two tasks. The rst 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 rst function that converts its arguments from Caml Light values to C
values, call the rst function, and convert the returned C value to Caml Light value. For instance,
here is the stub code for the input primitive:
value input(channel, buffer, offset, length)
value channel, buffer, offset, length;
{
return Val_long(getblock((struct channel *) channel,
&Byte(buffer, Long_val(offset)),
Long_val(length)));
}
(Here, Val_long, Long_val and so on are conversion macros for the type value, that will be
described later.) The hard work is performed by the function getblock, which is declared as:
long getblock(channel, p, n)
struct channel * channel;
char * p;
long n;
{
...
}
To write C code that operates on Caml Light values, the following include les are provided:
Chapter 12. Interfacing C with Caml Light 101
Include le Provides
mlvalues.h denition of the value type, and conversion macros
alloc.h allocation functions (to create structured Caml Light objects)
memory.h miscellaneous memory-related functions (for in-place modication of
structures, etc).
These les reside in the Caml Light standard library directory (usually /usr/local/lib/caml-light).
12.1.3 Linking C code with Caml Light code
The Caml Light runtime system comprises three main parts: the bytecode interpreter, the mem-
ory manager, and a set of C functions that implement the primitive operations. Some bytecode
instructions are provided to call these C functions, designated by their oset in a table of functions
(the table of primitives).
In the default mode, the Caml Light linker produces bytecode for the standard runtime system,
with a standard set of primitives. References to primitives that are not in this standard set result
in the \unavailable C primitive" error.
In the \custom runtime" mode, the Caml Light linker scans the bytecode object les (.zo les)
and determines the set of required primitives. Then, it builds a suitable runtime system, by calling
the native code linker with:
the table of the required primitives
a library that provides the bytecode interpreter, the memory manager, and the standard
primitives
libraries and object code les (.o les) mentioned on the command line for the Caml Light
linker, that provide implementations for the user's primitives.
This builds a runtime system with the required primitives. The Caml Light linker generates byte-
code 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 le (custom runtime + bytecode)
is launched.
To link in \custom runtime" mode, execute the camlc command with:
the -custom option
the names of the desired Caml Light object les (.zo les)
the names of the C object les and libraries (.o and .a les) that implement the required
primitives. (Libraries can also be specied with the usual -l syntax.)
Field(v; n) returns the value contained in the nth eld of the structured block v . Fields are
numbered from 0 to Wosize_val(v ) ? 1.
Code_val(v ) returns the code part of the closure v .
Byte(v; n) returns the nth character of the string v , with type char. Characters are numbered
from 0 to string_length(v ) ? 1.
Byte_u(v; n) returns the nth character of the string v , with type unsigned char. Characters
are numbered from 0 to string_length(v ) ? 1.
String_val(v ) returns a pointer to the rst byte of the string v , with type char *. This
pointer is a valid C string: there is a null character after the last character in the string.
However, Caml Light strings can contain embedded null characters, that will confuse the
usual C functions over strings.
Double_val(v) returns the
oating-point number contained in value v, with type double.
The expressions Field(v; n), Code_val(v ), Env_val(v ), Byte(v; n), Byte_u(v; n) and
Double_val(v ) are valid l-values. Hence, they can be assigned to, resulting in an in-place
modication of value v . Assigning directly to Field(v; n) must be done with care to avoid
confusing the garbage collector (see below).
12.4.4 Allocating blocks
From the standpoint of the allocation functions, blocks are divided according to their size as zero-
sized blocks, small blocks (with size less than or equal to Max_young_wosize), and large blocks
(with size greater than to Max_young_wosize). The constant Max_young_wosize is declared in the
include le mlvalues.h. It is guaranteed to be at least 64 (words), so that any block with constant
size less than or equal to 64 can be assumed to be small. For blocks whose size is computed at
run-time, the size must be compared against Max_young_wosize to determine the correct allocation
procedure.
Atom(t) returns an \atom" (zero-sized block) with tag t. Zero-sized blocks are preallocated
outside of the heap. It is incorrect to try and allocate a zero-sized block using the functions
below. For instance, Atom(0) represents (), false and []; Atom(1) represents true. (As a
convenience, mlvalues.h denes the macros Val_unit, Val_false and Val_true.)
Chapter 12. Interfacing C with Caml Light 105
alloc(n; t) returns a fresh small block of size n Max_young_wosize words, with tag t. If
this block is a structured block (i.e. if t < No_scan_tag), then the elds of the block (initially
containing garbage) must be initialized with legal values (using direct assignment to the elds
of the block) before the next allocation.
alloc_tuple(n) returns a fresh small block of size n Max_young_wosize words, with tag
0. The elds of this block must be lled with legal values before the next allocation or
modication.
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 ecient to call
alloc instead of alloc_shr.) If this block is a structured block (i.e. if t < No_scan_tag),
then the elds of the block (initially containing garbage) must be initialized with legal values
(using the initialize function described below) before the next allocation.
alloc_string(n) returns a string value of length n characters. The string initially contains
garbage.
copy_string(s) returns a string value containing a copy of the null-terminated C string s (a
char *).
alloc_array(f; a) allocates an array of values, calling function f over each element of the
input array a to transform it into a value. The array a is an array of pointers terminated
by the null pointer. The function f receives each pointer as argument, and returns a value.
The zero-tagged block returned by alloc_array(f; a) is lled with the values returned by
the successive calls to f .
copy_string_array(p) allocates an array of strings, copied from the pointer to a string array
p (a char **).
12.4.5 Raising exceptions
C functions cannot raise arbitrary exceptions. However, two functions are provided to raise two
standard exceptions:
failwith(s), where s is a null-terminated C string (with type char *), raises exception
Failure with argument s.
invalid_argument(s), where s is a null-terminated C string (with type char *), raises ex-
ception Invalid_argument with argument s.
The \cons" cell allocated rst needs to survive the allocation of the other cons cell; hence, the value
returned by the rst call to alloc must be stored in a registered root. The value returned by the
second call to alloc can reside in the un-registered local variable result, since we won't do any
further allocation in this function.
In the example above, the list is built bottom-up. Here is an alternate way, that proceeds
top-down. It is less ecient, but illustrates the use of modify.
value alloc_list_int(i1, i2)
int i1, i2;
{
value tail;
Push_roots(r, 1);
r[0] = alloc(2, 1); /* Allocate a cons cell */
Field(r[0], 0) = Val_int(i1); /* car = the integer i1 */
Field(r[0], 1) = Val_int(0); /* A dummy value
tail = alloc(2, 1); /* Allocate the other cons cell */
Field(tail, 0) = Val_int(i2); /* car = the integer i2 */
Field(tail, 1) = Atom(0); /* cdr = the empty list [] */
modify(&Field(r[0], 1), tail); /* cdr of the result = tail */
Pop_roots();
return r[0];
}
It would be incorrect to perform Field(r[0], 1) = tail directly, because the allocation of tail
has taken place since r[0] was allocated.
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 le, curses.o, looks like:
#include <curses.h>
#include <mlvalues.h>
value curses_initscr(unit)
value unit;
{
return (value) initscr(); /* OK to coerce directly from WINDOW * to value
since that's a block created by malloc() */
}
value curses_wrefresh(win)
value win;
{
wrefresh((WINDOW *) win);
return Val_unit;
}
value curses_addch(c)
value c;
{
Chapter 12. Interfacing C with Caml Light 109
addch(Int_val(c)); /* Characters are encoded like integers */
return Val_unit;
}
value curses_addstr(s)
value s;
{
addstr(String_val(s));
return Val_unit;
}
(Actually, it would be better to create a library for the stub code, with each stub code function
in a separate le, so that linking would pick only those functions from the curses library that are
actually used.)
The le curses.c can be compiled with:
cc -c -I/usr/local/lib/caml-light curses.c
(When passed a .c le, the camlc command simply calls cc on that le, with the right -I option.)
Now, here is a sample Caml Light program test.ml that uses the curses module:
#open "curses";;
let main_window = initscr () in
let small_window = newwin 10 5 20 10 in
mvwaddstr main_window 10 2 "Hello";
mvwaddstr small_window 4 3 "world";
refresh();
for i = 1 to 100000 do () done;
endwin()
;;
111
Chapter 13
Conventions
For easy reference, the modules are listed below in alphabetical order of module names. For each
module, the declarations from its interface le are printed one by one in typewriter font, followed
by a short comment. All modules and the identiers they export are indexed at the end of this
report.
113
114
value prefix && : bool -> bool -> bool
value prefix or : bool -> bool -> bool
value prefix || : bool -> bool -> bool
The boolean and is written e1 & e2 or e1 && e2. The boolean or is written e1 or e2 or
e1 || e2. Both constructs are sequential, left-to-right: e2 is evaluated only if needed.
Actually, e1 & e2 is equivalent to if e1 then e2 else false, and e1 or e2 is equivalent
to if e1 then true else e2.
value prefix not : bool -> bool
The boolean negation.
value string_of_bool : bool -> string
Return a string representing the given boolean.
Return the character with the given ASCII code. Raise Invalid_argument "char_of_int"
if the argument is outside the range 0{255.
value string_of_char : char -> string
Return a string representing the given character, with special characters escaped following
the lexical conventions of Caml Light.
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.
Negation of prefix =.
value prefix < : 'a -> 'a -> bool
value prefix <= : 'a -> 'a -> bool
value prefix > : 'a -> 'a -> bool
value prefix >= : 'a -> 'a -> bool
Structural ordering functions. These functions coincide with the usual orderings over
integer, string and
oating-point numbers, and extend them to a total ordering over all
types. The ordering is compatible with prefix =. As in the case of prefix =, mutable
structures are compared by contents. Comparison between functional values raises
Invalid_argument. Comparison between cyclic structures may not terminate.
compare x y returns 0 if x=y, a negative integer if x<y, and a positive integer if x>y. The
same restrictions as for = apply. compare can be used as the comparison function required
by the set and map modules.
116
value min: 'a -> 'a -> 'a
e1 == e2 tests for physical equality of e1 and e2. On integers and characters, it is the same
as structural equality. On mutable structures, e1 == e2 is true if and only if physical
modication of e1 also aects e2. On non-mutable structures, the behavior of prefix == is
implementation-dependent, except that e1 == e2 implies e1 = e2.
value prefix != : 'a -> 'a -> bool
Raised by the garbage collector, when there is insucient memory to complete the
computation.
exception Invalid_argument of string
Raised by library functions to signal that the given arguments do not make sense.
exception Failure of string
Raised by library functions to signal that they are undened on the given arguments.
exception Not_found
Raised by search functions when the desired object could not be found.
exception Exit
This exception is not raised by any library function. It is provided for use in your programs.
value failwith : string -> 'a
Truncate the given
oat to an integer value. The result is unspecied if it falls outside the
range of representable integers.
value float_of_int : int -> float
Unary negation.
value prefix + : float -> float -> float
value prefix +. : float -> float -> float
value add_float : float -> float -> float
Addition.
value prefix - : float -> float -> float
value prefix -. : float -> float -> float
value sub_float : float -> float -> float
Subtraction.
value prefix * : float -> float -> float
value prefix *. : float -> float -> float
value mult_float : float -> float -> float
Product.
value prefix / : float -> float -> float
value prefix /. : float -> float -> float
value div_float : float -> float -> float
Division.
118
value prefix ** : float -> float -> float
value prefix **. : float -> float -> float
value power : float -> float -> float
Exponentiation.
value eq_float : float -> float -> bool
value prefix =. : float -> float -> bool
Negation of eq_float.
value prefix <. : float -> float -> bool
value lt_float : float -> float -> bool
value prefix >. : float -> float -> bool
value gt_float : float -> float -> bool
value prefix <=. : float -> float -> bool
value le_float : float -> float -> bool
value prefix >=. : float -> float -> bool
value ge_float : float -> float -> bool
Round the given
oat to an integer value. floor f returns the greatest integer value less
than or equal to f. ceil f returns the least integer value greater than or equal to f.
Chapter 13. The core library 119
value abs_float : float -> float
frexp f returns the pair of the signicant and the exponent of f (when f is zero, the
signicant x and the exponent n of f are equal to zero; when f is non-zero, they are dened
by f = x *. 2 ** n).
value ldexp : float -> int -> float
ldexp x n returns x *. 2 ** n.
Convert the given string to a
oat, in decimal. The result is unspecied if the given string is
not a valid representation of a
oat.
succ x is x+1.
value pred : int -> int
pred x is x-1.
value prefix + : int -> int -> int
value add_int : int -> int -> int
Addition.
value prefix - : int -> int -> int
value sub_int : int -> int -> int
Subtraction.
value prefix * : int -> int -> int
value mult_int : int -> int -> int
Multiplication.
value prefix / : int -> int -> int
value div_int : int -> int -> int
value prefix quo : int -> int -> int
Negation of eq_int.
Chapter 13. The core library 121
value lt_int : int -> int -> bool
value gt_int : int -> int -> bool
value le_int : int -> int -> bool
value ge_int : int -> int -> bool
Bitwise operations
value prefix land : int -> int -> int
Bitwise complement
value prefix lsl : int -> int -> int
value lshift_left : int -> int -> int
n lsr m shifts n to the right by m bits. This is a logical shift: zeroes are inserted regardless
of sign.
value prefix asr : int -> int -> int
value lshift_right : int -> int -> int
Convert the given string to an integer, in decimal (by default) or in hexadecimal, octal or
binary if the string begins with 0x, 0o or 0b. Raise Failure "int_of_string" if the given
string is not a valid representation of an integer.
Raised when an operation cannot complete, because the end of the le has been reached.
value stdin : in_channel
value std_in : in_channel
value stdout : out_channel
value std_out : out_channel
value stderr : out_channel
value std_err : out_channel
The standard input, standard output, and standard error output for the process. std_in,
std_out and std_err are respectively synonymous with stdin, stdout and stderr.
Flush all pending writes on std_out and std_err, and terminate the process, returning the
given status code to the operating system (usually 0 to indicate no errors, and a small
positive integer to indicate failure.) This function should be called at the end of all
standalone programs that output results on std_out or std_err; otherwise, the program
may appear to produce no output, or its output may be truncated.
Print a newline character on standard output, and
ush standard output. This can be used
to simulate line buering of standard output.
Print the string, followed by a newline character on standard error and
ush standard error.
124
Input functions on standard input
value read_line : unit -> string
Flush standard output, then read characters from standard input until a newline character
is encountered. Return the string of all characters read, without the newline character at
the end.
value read_int : unit -> int
Flush standard output, then read one line from standard input and convert it to an integer.
Raise Failure "int_of_string" if the line read is not a valid representation of an integer.
value read_float : unit -> float
Flush standard output, then read one line from standard input and convert it to a
oating-point number. The result is unspecied if the line read is not a valid representation
of a
oating-point number.
Open the named le for writing, and return a new output channel on that le, positionned
at the beginning of the le. The le is truncated to zero length if it already exists. It is
created if it does not already exists. Raise sys__Sys_error if the le could not be opened.
value open_out_bin : string -> out_channel
Same as open_out, but the le is opened in binary mode, so that no translation takes place
during writes. On operating systems that do not distinguish between text mode and binary
mode, this function behaves like open_out.
value open_out_gen : sys__open_flag list -> int -> string -> out_channel
open_out_gen mode rights filename opens the le named filename for writing, as
above. The extra argument mode specify the opening mode (see sys__open). The extra
argument rights species the le permissions, in case the le must be created (see
sys__open). open_out and open_out_bin are special cases of this function.
Flush the buer associated with the given output channel, performing all pending writes on
that channel. Interactive programs must be careful about
ushing std_out and std_err at
the right time.
Chapter 13. The core library 125
value output_char : out_channel -> char -> unit
output chan buff ofs len writes len characters from string buff, starting at oset ofs,
to the output channel chan. Raise Invalid_argument "output" if ofs and len do not
designate a valid substring of buff.
value output_byte : out_channel -> int -> unit
Write one 8-bit integer (as the single character with that code) on the given output channel.
The given integer is taken modulo 256.
value output_binary_int : out_channel -> int -> unit
Write one integer in binary format on the given output channel. The only reliable way to
read it back is through the input_binary_int function. The format is compatible across all
machines for a given version of Caml Light.
value output_value : out_channel -> 'a -> unit
Write the representation of a structured value of any type to a channel. Circularities and
sharing inside the value are detected and preserved. The object can be read back, by the
function input_value. The format is compatible across all machines for a given version of
Caml Light.
value output_compact_value : out_channel -> 'a -> unit
Same as output_value, but uses a dierent format, which occupies less space on the le,
but takes more time to generate and read back.
value seek_out : out_channel -> int -> unit
seek_out chan pos sets the current writing position to pos for channel chan. This works
only for regular les. On les of other kinds (such as terminals, pipes and sockets), the
behavior is unspecied.
value pos_out : out_channel -> int
Return the total length (number of characters) of the given channel. This works only for
regular les. On les of other kinds, the result is meaningless.
value close_out : out_channel -> unit
Close the given channel,
ushing all buered write operations. The behavior is unspecied if
any of the functions above is called on a closed channel.
126
General input functions
value open_in : string -> in_channel
Open the named le for reading, and return a new input channel on that le, positionned at
the beginning of the le. Raise sys__Sys_error if the le could not be opened.
value open_in_bin : string -> in_channel
Same as open_in, but the le is opened in binary mode, so that no translation takes place
during reads. On operating systems that do not distinguish between text mode and binary
mode, this function behaves like open_in.
value open_in_gen : sys__open_flag list -> int -> string -> in_channel
open_in_gen mode rights filename opens the le named filename for reading, as above.
The extra arguments mode and rights specify the opening mode and le permissions (see
sys__open). open_in and open_in_bin are special cases of this function.
Read one character from the given input channel. Raise End_of_file if there are no more
characters to read.
value input_line : in_channel -> string
Read characters from the given input channel, until a newline character is encountered.
Return the string of all characters read, without the newline character at the end. Raise
End_of_file if the end of the le is reached at the beginning of line.
value input : in_channel -> string -> int -> int -> int
input chan buff ofs len attempts to read len characters from channel chan, storing
them in string buff, starting at character number ofs. It returns the actual number of
characters read, between 0 and len (inclusive). A return value of 0 means that the end of
le was reached. A return value between 0 and len exclusive means that no more characters
were available at that time; input must be called again to read the remaining characters, if
desired. Exception Invalid_argument "input" is raised if ofs and len do not designate a
valid substring of buff.
value really_input : in_channel -> string -> int -> int -> unit
really_input chan buff ofs len reads len characters from channel chan, storing them
in string buff, starting at character number ofs. Raise End_of_file if the end of le is
reached before len characters have been read. Raise Invalid_argument "really_input" if
ofs and len do not designate a valid substring of buff.
Chapter 13. The core library 127
value input_byte : in_channel -> int
Same as input_char, but return the 8-bit integer representing the character. Raise
End_of_file if an end of le was reached.
Read an integer encoded in binary format from the given input channel. See
output_binary_int. Raise End_of_file if an end of le was reached while reading the
integer.
value input_value : in_channel -> 'a
seek_in chan pos sets the current reading position to pos for channel chan. This works
only for regular les. On les of other kinds, the behavior is unspecied.
value pos_in : in_channel -> int
Return the total length (number of characters) of the given channel. This works only for
regular les. On les of other kinds, the result is meaningless.
value close_in : in_channel -> unit
Close the given channel. Anything can happen if any of the functions above is called on a
closed channel.
List concatenation.
128
value hd : 'a list -> 'a
Return the rst element of the given list. Raise Failure "hd" if the list is empty.
value tl : 'a list -> 'a list
Return the given list without its rst element. Raise Failure "tl" if the list is empty.
value rev : 'a list -> 'a list
List reversal.
value 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.
value do_list : ('a -> unit) -> 'a list -> unit
do_list f [a1; ...; an] applies function f in turn to a1; ...; an, discarding all the
results. It is equivalent to begin f a1; f a2; ...; f an; () end.
value it_list : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
value list_it : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
value map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
map2 f [a1; ...; an] [b1; ...; bn] is [f a1 b1; ...; f an bn]. Raise
Invalid_argument "map2" if the two lists have dierent lengths.
value do_list2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit
do_list2 f [a1; ...; an] [b1; ...; bn] calls in turn f a1 b1; ...; f an bn,
discarding the results. Raise Invalid_argument "do_list2" if the two lists have dierent
lengths.
value it_list2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b list -> 'c list -> 'a
Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)] is
([a1; ...; an], [b1; ...; bn])
value combine : 'a list * 'b list -> ('a * 'b) list
Transform a pair of lists into a list of pairs: combine ([a1; ...; an], [b1; ...; bn]) is
[(a1,b1); ...; (an,bn)]. Raise Invalid_argument "combine" if the two lists have
dierent lengths.
value map_combine : ('a * 'b -> 'c) -> 'a list * 'b list -> 'c list
map_combine f ([a1; ...; an], [b1; ...; bn]) is [f (a1, b1); ...; f (an, bn)].
Raise invalid_argument "map_combine" if the two lists have dierent lengths.
value do_list_combine : ('a * 'b -> unit) -> 'a list * 'b list -> unit
The type of references (mutable indirection cells) containing a value of type 'a.
value prefix ! : 'a ref -> 'a
!r returns the current contents of reference r. Could be dened as fun (ref x) -> x.
Raised by parsers when none of the rst component of the stream patterns is accepted
exception Parse_error
Raised by parsers when the rst component of a stream pattern is accepted, but one of the
following components is rejected
value stream_next : 'a stream -> 'a
stream_next s returns the rst element of stream s, and removes it from the stream. Raise
Parse_failure if the stream is empty.
value stream_from : (unit -> 'a) -> 'a stream
stream_from f returns the stream which fetches its terminals using the function f. This
function could be dened as:
let rec stream_from f = [< 'f(); stream_from f >]
but is implemented more eciently.
value stream_of_string : string -> char stream
do_stream f s scans the whole stream s, applying the function f in turn to each terminal
encountered
value stream_check : ('a -> bool) -> 'a stream -> 'a
stream_check p returns the parser which returns the rst terminal of the stream if the
predicate p returns true on this terminal, and raises Parse_failure otherwise.
value end_of_stream : 'a stream -> unit
stream_get s return the rst element of the stream s, and a stream containing the
remaining elements of s. Raise Parse_failure if the stream is empty. The stream s is not
modied. This function makes it possible to access a stream non-destructively.
132
13.16 string : string operations
value string_length : string -> int
s1 ^ s2 returns a fresh string containing the concatenation of the strings s1 and s2.
value concat : string list -> string
Return a fresh string containing the concatenation of all the strings in the argument list.
value sub_string : string -> int -> int -> string
sub_string s start len returns a fresh string of length len, containing the characters
number start to start + len - 1 of string s. Raise Invalid_argument "sub_string" if
start and len do not designate a valid substring of s; that is, if start < 0, or len < 0, or
start + len > string_length s.
create_string n returns a fresh string of length n. The string initially contains arbitrary
characters.
value make_string : int -> char -> string
fill_string s start len c modies string s in place, replacing the characters number
start to start + len - 1 by c. Raise Invalid_argument "fill_string" if start and
len do not designate a valid substring of s.
Chapter 13. The core library 133
value blit_string : string -> int -> string -> int -> int -> unit
blit_string s1 o1 s2 o2 len copies len characters from string s1, starting at character
number o1, to string s2, starting at character number o2. It works correctly even if s1 and
s2 are the same string, and the source and destination chunks overlap. Raise
Invalid_argument "blit_string" if o1 and len do not designate a valid substring of s1,
or if o2 and len do not designate a valid substring of s2.
value replace_string : string -> string -> int -> unit
replace_string dest src start copies all characters from the string src into the string
dst, starting at character number start in dst. Raise
Invalid_argument "replace_string" if copying would over
ow string dest.
Return a copy of the argument, with special characters represented by escape sequences,
following the lexical conventions of Caml Light.
value index_char: string -> char -> int
Same as index_char and rindex_char, but start searching at the character position given
as second argument. index_char s c is equivalent to index_char_from s 0 c, and
rindex_char s c to rindex_char_from s (string_length s - 1) c.
134
13.17 vect : operations on vectors
value vect_length : 'a vect -> int
vect_item v n returns the element number n of vector v. The rst element has number 0.
The last element has number vect_length v - 1. Raise Invalid_argument "vect_item"
if n is outside the range 0 to (vect_length v - 1). You can also write v.(n) instead of
vect_item v n.
value vect_assign : 'a vect -> int -> 'a -> unit
make_vect n x returns a fresh vector of length n, initialized with x. All the elements of this
new vector are initially physically equal to x (see module eq). Consequently, if x is mutable,
it is shared among all elements of the vector, and modifying x through one of the vector
entries will modify all other entries at the same time.
value make_matrix : int -> int -> 'a -> 'a vect vect
make_matrix dimx dimy e returns a two-dimensional array (a vector of vectors) with rst
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).
value init_vect : int -> (int -> 'a) -> 'a vect
value sub_vect : 'a vect -> int -> int -> 'a vect
sub_vect v start len returns a fresh vector of length len, containing the elements
number start to start + len - 1 of vector v. Raise Invalid_argument "sub_vect" if
start and len do not designate a valid subvector of v; that is, if start < 0, or len < 0, or
start + len > vect_length v.
copy_vect v returns a copy of v, that is, a fresh vector containing the same elements as v.
Chapter 13. The core library 135
value fill_vect : 'a vect -> int -> int -> 'a -> unit
fill_vect v ofs len x modies the vector v in place, storing x in elements number ofs
to ofs + len - 1. Raise Invalid_argument "fill_vect" if ofs and len do not designate
a valid subvector of v.
value blit_vect : 'a vect -> int -> 'a vect -> int -> int -> unit
blit_vect v1 o1 v2 o2 len copies len elements from vector v1, starting at element
number o1, to vector v2, starting at element number o2. It works correctly even if v1 and
v2 are the same vector, and the source and destination chunks overlap. Raise
Invalid_argument "blit_vect" if o1 and len do not designate a valid subvector of v1, or
if o2 and len do not designate a valid subvector of v2.
value list_of_vect : 'a vect -> 'a list
map_vect f v applies function f to all the elements of v, and builds a vector with the
results returned by f: [| f v.(0); f v.(1); ...; f v.(vect_length v - 1) |].
value map_vect_list : ('a -> 'b) -> 'a vect -> 'b list
map_vect_list f v applies function f to all the elements of v, and builds a list with the
results returned by f: [ f v.(0); f v.(1); ...; f v.(vect_length v - 1) ].
value do_vect : ('a -> unit) -> 'a vect -> unit
do_vect f v applies function f in turn to all the elements of v, discarding all the results:
f v.(0); f v.(1); ...; f v.(vect_length v - 1); ().
136
Chapter 14
Conventions
For easy reference, the modules are listed below in alphabetical order of module names. For each
module, the declarations from its interface le are printed one by one in typewriter font, followed
by a short comment. All modules and the identiers they export are indexed at the end of this
report.
parse speclist anonfun parses the command line, calling the functions in speclist
whenever appropriate, and anonfun on anonymous arguments. The functions are called in
the same order as they appear on the command line. The strings in the
(string * spec) list are keywords and must start with a -, else they are ignored. For
the user to be able to specify anonymous arguments starting with a -, include for example
("--", String anonfun) in speclist.
Functions in speclist or anonfun can raise Bad with an error message to reject invalid
arguments.
The type of trees containing elements of type 'a. Empty is the empty tree (containing no
elements).
type 'a contents = Nothing | Something of 'a
Used with the functions modify and split, to represent the presence or the absence of an
element in a tree.
Chapter 14. The standard library 139
value add: ('a -> int) -> 'a -> 'a t -> 'a t
add f x t inserts the element x into the tree t. f is an ordering function: f y must return
0 if x and y are equal (or equivalent), a negative integer if x is smaller than y, and a positive
integer if x is greater than y. The tree t is returned unchanged if it already contains an
element equivalent to x (that is, an element y such that f y is 0). The ordering f must be
consistent with the orderings used to build t with add, remove, modify or split operations.
value contains: ('a -> int) -> 'a t -> bool
contains f t checks whether t contains an element satisfying f, that is, an element x such
that f x is 0. f is an ordering function withthe same constraints as for add. It can be
coarser (identify more elements) than the orderings used to build t, but must be consistent
with them.
value find: ('a -> int) -> 'a t -> 'a
Same as contains, except that find f t returns the element x such that f x is 0, or raises
Not_found if none has been found.
split f t returns a triple (less, elt, greater) where less is a tree containing all
elements x of t such that f x is negative, greater is a tree containing all elements x of t
such that f x is positive, and elt is Something x if t contains an element x such that f x
is 0, and Nothing otherwise.
value compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
Compare two trees. The rst argument f is a comparison function over the tree elements:
f e1 e2 is zero if the elements e1 and e2 are equal, negative if e1 is smaller than e2, and
positive if e1 is greater than e2. compare f t1 t2 compares the fringes of t1 and t2 by
lexicographic extension of f.
140
14.3 filename : operations on le names
value current_dir_name : string
concat dir file returns a le name that designates le file in directory dir.
value is_absolute : string -> bool
Return true if the le name is absolute or starts with an explicit reference to the current
directory (./ or ../ in Unix), and false if it is relative to the current directory.
value check_suffix : string -> string -> bool
check_suffix name suff returns true if the lename name ends with the sux suff.
value chop_suffix : string -> string -> string
chop_suffix name suff removes the sux suff from the lename name. The behavior is
undened if name does not end with the sux suff.
value basename : string -> string
value dirname : string -> string
Boxes
value open_box : int -> unit
open_box d opens a new pretty-printing box with oset d. This box is the general purpose
pretty-printing box. Material in this box is displayed \horizontal or vertical": break hints
inside the box may lead to a new line, if there is no more room on the line to print the
remainder of the box, or if a new line may lead to a new indentation (demonstrating the
indentation of the box). When a new line is printed in the box, d is added to the current
indentation.
value close_box : unit -> unit
Close the most recently opened pretty-printing box.
Formatting functions
value print_string : string -> unit
print_string str prints str in the current box.
value print_as : int -> string -> unit
print_as len str prints str in the current box. The pretty-printer formats str as if it
were of length len.
value print_int : int -> unit
Print an integer in the current box.
value print_float : float -> unit
Print a
oating point number in the current box.
value print_char : char -> unit
Print a character in the current box.
value print_bool : bool -> unit
Print an boolean in the current box.
142
Break hints
value print_space : unit -> unit
print_space () is used to separate items (typically to print a space between two words). It
indicates that the line may be split at this point. It either prints one space or splits the line.
It is equivalent to print_break 1 0.
value print_cut : unit -> unit
print_cut () is used to mark a good break position. It indicates that the line may be split
at this point. It either prints nothing or splits the line. This allows line splitting at the
current point, without printing spaces or adding indentation. It is equivalent to
print_break 0 0.
Insert a break hint in a pretty-printing box. print_break nspaces offset indicates that
the line may be split (a newline character is printed) at this point, if the contents of the
current box does not t on one line. If the line is split at that point, offset is added to the
current indentation. If the line is not split, nspaces spaces are printed.
value print_flush : unit -> unit
Flush the pretty printer: all opened boxes are closed, and all pending text is displayed.
value print_newline : unit -> unit
Force a newline in the current box. Not the normal way of pretty-printing, you should
prefer break hints.
value print_if_newline : unit -> unit
Execute the next formatting command if the preceding line has just been split. Otherwise,
ignore the next formatting command.
Margin
value set_margin : int -> unit
set_margin d sets the value of the right margin to d (in characters): this value is used to
detect line over
ows that leads to split lines. Nothing happens if d is smaller than 2 or
bigger than 999999999.
value get_margin : unit -> int
set_max_indent d sets the value of the maximum indentation limit to d (in characters):
once this limit is reached, boxes are rejected to the left, if they do not t on the current line.
Nothing happens if d is smaller than 2 or bigger than 999999999.
value get_max_indent : unit -> int
set_max_boxes max sets the maximum number of boxes simultaneously opened. Material
inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by
get_ellipsis_text ()). Nothing happens if max is not greater than 1.
Advanced formatting
value open_hbox : unit -> unit
open_hbox () opens a new pretty-printing box. This box is \horizontal": the line is not
split in this box (new lines may still occur inside boxes nested deeper).
value open_vbox : int -> unit
open_vbox d opens a new pretty-printing box with oset d. This box is \vertical": every
break hint inside this box leads to a new line. When a new line is printed in the box, d is
added to the current indentation.
value open_hvbox : int -> unit
open_hovbox d opens a new pretty-printing box with oset d. This box is \horizontal or
vertical": break hints inside this box may lead to a new line, if there is no more room on the
line to print the remainder of the box. When a new line is printed in the box, d is added to
the current indentation.
144
Tabulations
value open_tbox : unit -> unit
Open a tabulation box.
value close_tbox : unit -> unit
Close the most recently opened tabulation box.
value print_tbreak : int -> int -> unit
Break hint in a tabulation box. print_tbreak spaces offset moves the insertion point to
the next tabulation (spaces being added to this position). Nothing occurs if insertion point
is already on a tabulation mark. If there is no next tabulation on the line, then a newline is
printed and the insertion point moves to the rst tabulation of the box. If a new line is
printed, offset is added to the current indentation.
value set_tab : unit -> unit
Set a tabulation mark at the current insertion point.
value print_tab : unit -> unit
print_tab () is equivalent to print_tbreak (0,0).
Ellipsis
value set_ellipsis_text : string -> unit
Set the text of the ellipsis printed when too many boxes are opened (a single dot, ., by
default).
value get_ellipsis_text : unit -> string
Return the text of the ellipsis.
Abstract data type corresponding to a pretty-printer and all its machinery. Dening new
pretty-printers permits the output of material in parallel on several channels. Parameters of
the pretty-printer are local to the pretty-printer: margin, maximum indentation limit,
maximum number of boxes simultaneously opened, ellipsis, and so on, are specic to each
pretty-printer and may be xed independently. A new formatter is obtained by calling the
make_formatter function.
The standard formatter used by the formatting functions above. It is dened using
make_formatter with output function output stdout and
ushing function
fun () -> flush stdout.
A formatter to use with formatting functions below for output to standard error. It is
dened using make_formatter with output function output stderr and
ushing function
fun () -> flush stderr.
value make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter
make_formatter out flush returns a new formatter that writes according to the output
function out, and
ushing function flush. Hence, a formatter to out channel oc is returned
by make_formatter (output oc) (fun () -> flush oc).
value pp_open_hbox : formatter -> unit -> unit
value pp_open_vbox : formatter -> int -> unit
value pp_open_hvbox : formatter -> int -> unit
value pp_open_hovbox : formatter -> int -> unit
value pp_open_box : formatter -> int -> unit
value pp_close_box : formatter -> unit -> unit
value pp_print_string : formatter -> string -> unit
value pp_print_as : formatter -> int -> string -> unit
value pp_print_int : formatter -> int -> unit
value pp_print_float : formatter -> float -> unit
value pp_print_char : formatter -> char -> unit
value pp_print_bool : formatter -> bool -> unit
value pp_print_break : formatter -> int -> int -> unit
value pp_print_cut : formatter -> unit -> unit
value pp_print_space : formatter -> unit -> unit
value pp_force_newline : formatter -> unit -> unit
value pp_print_flush : formatter -> unit -> unit
value pp_print_newline : formatter -> unit -> unit
value pp_print_if_newline : formatter -> unit -> unit
146
value pp_open_tbox : formatter -> unit -> unit
value pp_close_tbox : formatter -> unit -> unit
value pp_print_tbreak : formatter -> int -> int -> unit
value pp_set_tab : formatter -> unit -> unit
value pp_print_tab : formatter -> unit -> unit
value pp_set_margin : formatter -> int -> unit
value pp_get_margin : formatter -> unit -> int
value pp_set_max_indent : formatter -> int -> unit
value pp_get_max_indent : formatter -> unit -> int
value pp_set_max_boxes : formatter -> int -> unit
value pp_get_max_boxes : formatter -> unit -> int
value pp_over_max_boxes : formatter -> unit -> bool
value pp_set_ellipsis_text : formatter -> string -> unit
value pp_get_ellipsis_text : formatter -> unit -> string
value pp_set_formatter_out_channel : formatter -> out_channel -> unit
value pp_set_formatter_output_functions : formatter ->
(string -> int -> int -> unit) -> (unit -> unit) -> unit
value pp_get_formatter_output_functions :
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
The basic functions to use with formatters. These functions are the basic ones: usual
functions operating on the standard formatter are dened via partial evaluation of these
primitives. For instance, print_string is equal to pp_print_string std_formatter.
value fprintf : formatter -> ('a, formatter, unit) format -> 'a
fprintf ff format arg1 ... argN formats the arguments arg1 to argN according to the
format string format, and outputs the resulting string on the formatter ff. The format is a
character string which contains three types of objects: plain characters and conversion
specications as specied in the printf module, and pretty-printing indications. The
pretty-printing indication characters are introduced by a @ character, and their meanings
are:
[: open a pretty-printing box. The type and oset of the box may be optionally specied
with the following syntax: the < character, followed by an optional box type indication, then
an optional integer oset, and the closing > character. Box type is one of h, v, hv, or hov,
which stand respectively for an horizontal, vertical, \horizontal-vertical" and \horizontal or
vertical" box.
]: close the most recently opened pretty-printing box.
,: output a good break as with print_cut ().
: output a space, as with print_space ().
\n: force a newline, as with force_newline ().
;: output a good break as with print_break. The nspaces and offset parameters of the
break may be optionally specied with the following syntax: the < character, followed by an
integer nspaces value, then an integer oset, and a closing > character.
.:
ush the pretty printer as with print_newline ().
@: a plain @ character.
Chapter 14. The standard library 147
value printf : ('a, formatter, unit) format -> 'a
The memory management counters are returned in a stat record. All the numbers are
computed since the start of the program. The elds of this record are:
minor_words Number of words allocated in the minor heap.
promoted_words Number of words allocated in the minor heap that survived a minor
collection and were moved to the major heap.
major_words Number of words allocated in the major heap, including the promoted words.
minor_collections Number of minor collections.
major_collections Number of major collection cycles, not counting the current cycle.
heap_words Total size of the major heap, in words.
heap_chunks Number of times the major heap size was increased.
live_words Number of words of live data in the major heap, including the header words.
live_blocks Number of live objects in the major heap.
free_words Number of words in the free list.
free_blocks Number of objects in the free list.
largest_words Size (in words) of the largest object in the free list.
fragments Number of wasted words due to fragmentation. These are 1-words free blocks
placed between two live objects. They cannot be inserted in the free list, thus they are not
available for allocation.
148
The total amount of memory allocated by the program is (in words)
minor_words + major_words - promoted_words. Multiply by the word size (4 on a 32-bit
machine, 8 on a 64-bit machine) to get the number of bytes.
type control = {
mutable minor_heap_size : int;
mutable major_heap_increment : int;
mutable space_overhead : int;
mutable verbose : bool
}
Return the current values of the memory management counters in a stat record.
value print_stat : io__out_channel -> unit
Print the current values of the memory management counters (in human-readable form)
into the channel argument.
value get : unit -> control
set r changes the GC parameters according to the control record r. The normal usage is:
let r = gc__get () in (* Get the current parameters. *)
r.verbose <- true; (* Change some of them. *)
gc__set r (* Set the new values. *)
Finish the current major collection cycle and perform a complete new cycle. This will
collect all currently unreachable objects.
The type of tokens. The lexical classes are: Int and Float for integer and
oating-point
numbers; String for string literals, enclosed in double quotes; Char for character literals,
enclosed in backquotes; Ident for identiers (either sequences of letters, digits, underscores
and quotes, or sequences of \operator characters" such as +, *, etc); and Kwd for keywords
(either identiers or single \special characters" such as (, }, etc).
value make_lexer: string list -> (char stream -> token stream)
Construct the lexer function. The rst argument is the list of keywords. An identier s is
returned as Kwd s if s belongs to this list, and as Ident s otherwise. A special character s
is returned as Kwd s if s belongs to this list, and cause a lexical error (exception
Parse_error) otherwise. Blanks and newlines are skipped. Comments delimited by (* and
*) are skipped as well, and can be nested.
The associated parser would be a function from token stream to, for instance, int, and
would have rules such as:
150
let parse_expr = function
[< 'Int n >] -> n
| [< 'Kwd "("; parse_expr n; 'Kwd ")" >] -> n
| [< parse_expr n1; (parse_remainder n1) n2 >] -> n2
and parse_remainder n1 = function
[< 'Kwd "+"; parse_expr n2 >] -> n1+n2
| ...
new n creates a new, empty hash table, with initial size n. The table grows as needed, so n
is just an initial guess. Better results are said to be achieved when n is a prime number.
Raise Invalid_argument "hashtbl__new" if n is less than 1.
value clear : ('a, 'b) t -> unit
add tbl x y adds a binding of x to y in table tbl. Previous bindings for x are not
removed, but simply hidden. That is, after performing remove tbl x, the previous binding
for x, if any, is restored. (This is the semantics of association lists.)
value find : ('a, 'b) t -> 'a -> 'b
find tbl x returns the current binding of x in tbl, or raises Not_found if no such binding
exists.
value find_all : ('a, 'b) t -> 'a -> 'b list
find_all tbl x returns the list of all data associated with x in tbl. The current binding is
returned rst, then the previous bindings, in reverse order of introduction in the table.
value remove : ('a, 'b) t -> 'a -> unit
remove tbl x removes the current binding of x in tbl, restoring the previous binding if it
exists. It does nothing if x is not bound in tbl.
Chapter 14. The standard library 151
value do_table : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
do_table f tbl applies f to all bindings in table tbl, discarding all the results. f receives
the key as rst 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
unpredictable, except that successive bindings for the same key are presented in reverse
chronological order (most recent rst).
value do_table_rev : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
Same as do_table, except that successive bindings for the same key are presented in
chronological order (oldest rst).
hash x associates a positive integer to any value of any type. It is guaranteed that if x = y,
then hash x = hash y. Moreover, hash always terminates, even on cyclic structures.
value hash_param : int -> int -> 'a -> int
hash_param n m x computes a hash value for x, with the same properties as for hash. The
two extra parameters n and m give more precise control over hashing. Hashing performs a
depth-rst, right-to-left traversal of the structure x, stopping after n meaningful nodes were
encountered, or m nodes, meaningful or not, were encountered. Meaningful nodes are:
integers;
oating-point numbers; strings; characters; booleans; and constant constructors.
Larger values of m and n means that more nodes are taken into account to compute the nal
hash value, and therefore collisions are less likely to happen. However, hashing takes longer.
The parameters m and n govern the tradeo between accuracy and speed.
The type of lexer buers. A lexer buer is the argument passed to the scanning functions
dened by the generated scanners. The lexer buer holds the current state of the scanner,
plus a function to rell the buer from the input.
152
value create_lexer_channel : in_channel -> lexbuf
Create a lexer buer which reads from the given string. Reading starts from the rst
character in the string. An end-of-input condition is generated when the end of the string is
reached.
value create_lexer : (string -> int -> int) -> lexbuf
Create a lexer buer with the given function as its reading method. When the scanner needs
more characters, it will call the given function, giving it a character string s and a character
count n. The function should put n characters or less in s, starting at character number 0,
and return the number of characters provided. A return value of 0 means end of input.
get_lexeme_start lexbuf returns the position in the input stream of the rst character of
the matched string. The rst character of the stream has position 0.
value get_lexeme_end : lexbuf -> int
get_lexeme_end lexbuf returns the position in the input stream of the character following
the last character of the matched string. The rst character of the stream has position 0.
Chapter 14. The standard library 153
14.9 map : association tables over ordered types
This module implements applicative association tables, also known as nite maps or
dictionaries, given a total ordering function over the keys. All operations over maps are
purely applicative (no side-eects). The implementation uses balanced binary trees, and
therefore searching and insertion take time logarithmic in the size of the map.
type ('a, 'b) t
The type of maps from type 'a to type 'b.
value empty: ('a -> 'a -> int) -> ('a, 'b) t
The empty map. The argument is a total ordering function over the set elements. This is a
two-argument function f such that f e1 e2 is zero if the elements e1 and e2 are equal,
f e1 e2 is strictly negative if e1 is smaller than e2, and f e1 e2 is strictly positive if e1 is
greater than e2. Examples: a suitable ordering function for type int is prefix -. You can
also use the generic structural comparison function eq__compare.
value add: 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t
add x y m returns a map containing the same bindings as m, plus a binding of x to y.
Previous bindings for x in m are not removed, but simply hidden: they reappear after
performing a remove operation. (This is the semantics of association lists.)
value find:'a -> ('a, 'b) t -> 'b
find x m returns the current binding of x in m, or raises Not_found if no such binding exists.
value remove: 'a -> ('a, 'b) t -> ('a, 'b) t
remove x m returns a map containing the same bindings as m except the current binding for
x. The previous binding for x is restored if it exists. m is returned unchanged if x is not
bound in m.
value iter: ('a -> 'b -> unit) -> ('a, 'b) t -> unit
iter f m applies f to all bindings in map m, discarding the results. f receives the key as
rst argument, and the associated value as second argument. The order in which the
bindings are passed to f is unspecied. Only current bindings are presented to f: bindings
hidden by more recent bindings are not passed to f.
Same as symbol_start and symbol_end above, but return the position of the string
matching the nth item on the right-hand side of the rule, where n is the integer parameter
to lhs_start and lhs_end. n is 1 for the leftmost item.
value clear_parser : unit -> unit
Empty the parser stack. Call it just after a parsing function has returned, to remove all
pointers from the parser stack to structures that were built by semantic actions during
parsing. This is optional, but lowers the memory requirements of the programs.
exception Parse_error
The type of format strings. 'a is the type of the parameters of the string, 'c is the result
type for the printf-style function, and 'b is the type of the rst argument given to %a and
%t printing functions.
value fprintf: out_channel -> ('a, out_channel, unit) format -> 'a
fprintf outchan format arg1 ... argN formats the arguments arg1 to argN according
to the format string format, and outputs the resulting string on the channel outchan. The
format is a character string which contains two types of objects: plain characters, which are
simply copied to the output channel, and conversion specications, each of which causes
conversion and printing of one argument. Conversion specications consist in the %
character, followed by optional
ags and eld widths, followed by one conversion character.
The conversion characters and their meanings are:
d or i: convert an integer argument to signed decimal
Chapter 14. The standard library 155
u: convert an integer argument to unsigned decimal
x: convert an integer argument to unsigned hexadecimal, using lowercase letters.
X: convert an integer argument to unsigned hexadecimal, using uppercase letters.
s: insert a string argument
c: insert a character argument
f: convert a
oating-point argument to decimal notation, in the style dddd.ddd
e or E: convert a
oating-point argument to decimal notation, in the style d.ddd e+-dd
(mantissa and exponent)
g or G: convert a
oating-point argument to decimal notation, in style f or e, E (whichever
is more compact)
b: convert a boolean argument to the string true or false
a: user-dened printer. Takes two arguments and apply the rst one to outchan (the
current output channel) and to the second argument. The rst argument must therefore
have type out_channel -> 'b -> unit and the second 'b. The output produced by the
function is therefore inserted in the output of fprintf at the current point.
t: same as %a, but takes only one argument (with type out_channel -> unit) and apply it
to outchan.
Refer to the C library printf function for the meaning of
ags and eld width speciers. If
too few arguments are provided, printing stops just before converting the rst missing
argument.
value printf: ('a, out_channel, unit) format -> 'a
Same as fprintf, except that the result of the formatting is returned as a string instead of
being written on a channel.
value fprint: out_channel -> string -> unit
Print the given string on the given output channel, without any formatting. This is the
same function as output_string of module io.
value print: string -> unit
Print the given string on std_out, without any formatting. This is the same function as
print_string of module io.
Print the given string on std_err, without any formatting. This is the same function as
prerr_string of module io.
156
14.13 queue : queues
This module implements queues (FIFOs), with in-place modication.
type 'a t
take q removes and returns the rst element in queue q, or raises Empty if the queue is
empty.
value peek: 'a t -> 'a
peek q returns the rst element in queue q, without removing it from the queue, or raises
Empty if the queue is empty.
iter f q applies f in turn to all elements of q, from the least recently entered to the most
recently entered. The queue itself is unchanged.
Chapter 14. The standard library 157
14.14 random : pseudo-random number generator
value init : int -> unit
Initialize the generator, using the argument as a seed. The same seed will always yield the
same sequence of numbers.
value full_init : int vect -> unit
Same as init but takes more data as seed. It is not useful to give more than 55 integers.
value int : int -> int
random__int bound returns a random number between 0 (inclusive) and bound (exclusive).
bound must be positive and smaller than 230.
The empty set. The argument is a total ordering function over the set elements. This is a
two-argument function f such that f e1 e2 is zero if the elements e1 and e2 are equal,
f e1 e2 is strictly negative if e1 is smaller than e2, and f e1 e2 is strictly positive if e1 is
greater than e2. Examples: a suitable ordering function for type int is prefix -. You can
also use the generic structural comparison function eq__compare.
value is_empty: 'a t -> bool
Sort a list in increasing order according to an ordering predicate. The predicate should
return true if its rst argument is less than or equal to its second argument.
value merge : ('a -> 'a -> bool) -> 'a list -> 'a list -> 'a list
Merge two lists according to the given predicate. Assuming the two argument lists are
sorted according to the predicate, merge returns a sorted list containing the elements from
the two lists. The behavior is undened if the two argument lists were not sorted.
Chapter 14. The standard library 159
14.17 stack : stacks
This module implements stacks (LIFOs), with in-place modication.
type 'a t
pop s removes and returns the topmost element in stack s, or raises Empty if the stack is
empty.
value clear : 'a t -> unit
iter f s applies f in turn to all elements of s, from the element at the top of the stack to
the element at the bottom of the stack. The stack itself is unchanged.
Raised by some functions in the sys and io modules, when the underlying system calls fail.
The argument to Sys_error is a string describing the error. The texts of the error messages
are implementation-dependent, and should not be relied upon to catch specic system
errors.
160
value command_line : string vect
The command line arguments given to the process. The rst element is the command name
used to invoke the program.
value interactive: bool
True if we're running under the toplevel system. False if we're running as a standalone
program.
type file_perm == int
value s_irusr : file_perm
value s_iwusr : file_perm
value s_ixusr : file_perm
value s_irgrp : file_perm
value s_iwgrp : file_perm
value s_ixgrp : file_perm
value s_iroth : file_perm
value s_iwoth : file_perm
value s_ixoth : file_perm
value s_isuid : file_perm
value s_isgid : file_perm
value s_irall : file_perm
value s_iwall : file_perm
value s_ixall : file_perm
Terminate the program and return the given status code to the operating system. In
contrast with the function exit from module io, this exit function does not
ush the
standard output and standard error channels.
Chapter 14. The standard library 161
value open : string -> open_flag list -> file_perm -> int
Open a le. The second argument is the opening mode. The third argument is the
permissions to use if the le must be created. The result is a le descriptor opened on the
le.
value close : int -> unit
Close a le descriptor.
value remove : string -> unit
Rename a le. The rst argument is the old name and the second is the new name.
value getenv : string -> string
Return the value associated to a variable in the process environment. Raise Not_found if
the variable is unbound.
value chdir : string -> unit
Change the current working directory of the process. Note that there is no easy way of
getting the current working directory from the operating system.
value system_command : string -> int
Execute the given shell command and return its exit code.
value time : unit -> float
Return the processor time, in seconds, used by the program since the beginning of execution.
exception Break
catch_break governs whether user interrupt terminates the program or raises the Break
exception. Call catch_break true to enable raising Break, and catch_break false to let
the system terminate the program on user interrupt.
162
Chapter 15
y pixel at (x; y )
- x
x size_x()
163
164
Here are the graphics mode specications supported by open_graph on the various implementations
of this library.
Unix: The argument to open_graph has the format "display-name geometry ", where display-name
is the name of the X-windows display to connect to, and geometry is a standard X-windows
geometry specication. The two components are separated by a space. Either can be
omitted, or both. Examples:
open_graph "foo:0"
connects to the display foo:0 and creates a window with the default geometry
open_graph "foo:0 300x100+50-0"
connects to the display foo:0 and creates a window 300 pixels wide by 100 pixels tall,
at location (50; 0)
open_graph " 300x100+50-0"
connects to the default display and creates a window 300 pixels wide by 100 pixels tall,
at location (50; 0)
open_graph ""
connects to the default display and creates a window with the default geometry.
Mac: The argument to open_graph is ignored.
PC: The argument to open_graph has the format "widthxheight" or "widthxheight+x+y", where
width and height are the initial dimensions of the graphics windows, and x and y are the
position of the upper-left corner of the graphics window. If omitted, (width,height) default
to (600,400) and (x,y) default to (10, 10).
Initializations
value open_graph: string -> unit
Show the graphics window or switch the screen to graphic mode. The graphics window is
cleared. The string argument is used to pass optional information on the desired graphics
mode, the graphics window size, and so on. Its interpretation is implementation-dependent.
If the empty string is given, a sensible default is selected.
value close_graph: unit -> unit
Delete the graphics window or switch the screen back to text mode.
Chapter 15. The graphics library 165
value clear_graph : unit -> unit
Return the size of the graphics window. Coordinates of the screen pixels range over
0 .. size_x()-1 and 0 .. size_y()-1. Drawings outside of this rectangle are clipped,
without causing an error. The origin (0,0) is at the lower left corner.
Colors
type color == int
rgb r g b returns the integer encoding the color with red component r, green component
g, and blue component b. r, g and b are in the range 0..255.
Default background and foreground colors (usually, either black foreground on a white
background or white foreground on a black background). clear_graph lls the screen with
the background color. The initial drawing color is foreground.
166
Point and line drawing
value plot : int -> int -> unit
Plot the given point with the current drawing color.
value point_color : int -> int -> color
Return the color of the given point.
value moveto : int -> int -> unit
Position the current point.
value current_point : unit -> int * int
Return the position of the current point.
value lineto : int -> int -> unit
Draw a line with endpoints the current point and the given point, and move the current
point to the given point.
value draw_arc : int -> int -> int -> int -> int -> int -> unit
draw_arc x y rx ry a1 a2 draws an elliptical arc with center x,y, horizontal radius rx,
vertical radius ry, from angle a1 to angle a2 (in degrees). The current point is unchanged.
value draw_ellipse : int -> int -> int -> int -> unit
draw_ellipse x y rx ry draws an ellipse with center x,y, horizontal radius rx and
vertical radius ry. The current point is unchanged.
value draw_circle : int -> int -> int -> unit
draw_circle x y r draws a circle with center x,y and radius r. The current point is
unchanged.
value set_line_width : int -> unit
Set the width of points and lines drawn with the functions above. Under X Windows,
set_line_width 0 selects a width of 1 pixel and a faster, but less precise drawing
algorithm than the one used when set_line_width 1 is specied.
Text drawing
value draw_char : char -> unit
value draw_string : string -> unit
Draw a character or a character string with lower left corner at current position. After
drawing, the current position is set to the lower right corner of the text drawn.
value set_font : string -> unit
value set_text_size : int -> unit
Set the font and character size used for drawing text. The interpretation of the arguments
to set_font and set_text_size is implementation-dependent.
value text_size : string -> int * int
Return the dimensions of the given text, if it were drawn with the current font and size.
Chapter 15. The graphics library 167
Filling
value fill_rect : int -> int -> int -> int -> unit
fill_rect x y w h lls the rectangle with lower left corner at x,y, width w and heigth h,
with the current color.
value fill_poly : (int * int) vect -> unit
Fill the given polygon with the current color. The array contains the coordinates of the
vertices of the polygon.
value fill_arc : int -> int -> int -> int -> int -> int -> unit
Fill an elliptical pie slice with the current color. The parameters are the same as for
draw_arc.
value fill_ellipse : int -> int -> int -> int -> unit
Fill an ellipse with the current color. The parameters are the same as for draw_ellipse.
value fill_circle : int -> int -> int -> unit
Fill a circle with the current color. The parameters are the same as for draw_circle.
Images
type image
The abstract type for images, in internal representation. Externally, images are represented
as matrices of colors.
value transp : color
In matrices of colors, this color represent a \transparent" point: when drawing the
corresponding image, all pixels on the screen corresponding to a transparent pixel in the
image will not be modied, while other points will be set to the color of the corresponding
point in the image. This allows superimposing an image over an existing background.
value make_image : color vect vect -> image
Convert the given color matrix to an image. Each sub-array represents one horizontal line.
All sub-arrays must have the same length; otherwise, exception Graphic_failure is raised.
value dump_image : image -> color vect vect
Draw the given image with lower left corner at the given point.
168
value get_image : int -> int -> int -> int -> image
Capture the contents of a rectangle on the screen as an image. The parameters are the same
as for fill_rect.
value create_image : int -> int -> image
create_image w h returns a new image w pixels wide and h pixels tall, to be used in
conjunction with blit_image. The initial image contents are random.
value blit_image : image -> int -> int -> unit
blit_image img x y copies screen pixels into the image img, modifying img in-place. The
pixels copied are those inside the rectangle with lower left corner at x,y, and width and
height equal to those of the image.
To report events.
type event =
Button_down (* A mouse button is pressed *)
| Button_up (* A mouse button is released *)
| Key_pressed (* A key is pressed *)
| Mouse_motion (* The mouse is moved *)
| Poll (* Don't wait; return immediately *)
Wait until one of the events specied in the given event list occurs, and return the status of
the mouse and keyboard at that time. If Poll is given in the event list, return immediately
with the current status. If the mouse cursor is outside of the graphics window, the mouse_x
and mouse_y elds of the event are outside the range 0..size_x()-1, 0..size_y()-1.
Keypresses are queued, and dequeued one by one when the Key_pressed event is specied.
Chapter 15. The graphics library 169
Mouse and keyboard polling
value mouse_pos : unit -> int * int
Return the position of the mouse cursor, relative to the graphics window. If the mouse
cursor is outside of the graphics window, mouse_pos() returns a point outside of the range
0..size_x()-1, 0..size_y()-1.
Wait for a key to be pressed, and return the corresponding character. Keypresses are
queued.
value key_pressed : unit -> bool
Return true if a keypress is available; that is, if read_key would not block.
Sound
value sound : int -> int -> unit
sound freq dur plays a sound at frequency freq (in hertz) for a duration dur (in
milliseconds). On the Macintosh, the frequency is rounded to the nearest note in the
equal-tempered scale.
170
Chapter 16
171
172
| ENOMEM (* Not enough core *)
| EACCES (* Permission denied *)
| EFAULT (* Bad address *)
| ENOTBLK (* Block device required *)
| EBUSY (* Mount device busy *)
| EEXIST (* File exists *)
| EXDEV (* Cross-device link *)
| ENODEV (* No such device *)
| ENOTDIR (* Not a directory*)
| EISDIR (* Is a directory *)
| EINVAL (* Invalid argument *)
| ENFILE (* File table overflow *)
| EMFILE (* Too many open files *)
| ENOTTY (* Not a typewriter *)
| ETXTBSY (* Text file busy *)
| EFBIG (* File too large *)
| ENOSPC (* No space left on device *)
| ESPIPE (* Illegal seek *)
| EROFS (* Read-only file system *)
| EMLINK (* Too many links *)
| EPIPE (* Broken pipe *)
| EDOM (* Argument too large *)
| ERANGE (* Result too large *)
| 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 *)
| 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 *)
Chapter 16. The unix library: Unix system calls 173
| 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 *)
| ELOOP (* Too many levels of symbolic links *)
| ENAMETOOLONG (* File name too long *)
| EHOSTDOWN (* Host is down *)
| EHOSTUNREACH (* No route to host *)
| ENOTEMPTY (* Directory not empty *)
| EPROCLIM (* Too many processes *)
| EUSERS (* Too many users *)
| EDQUOT (* Disc quota exceeded *)
| ESTALE (* Stale NFS file handle *)
| EREMOTE (* Too many levels of remote in path *)
| EIDRM (* Identifier removed *)
| EDEADLK (* Deadlock condition. *)
| ENOLCK (* No record locks available. *)
| ENOSYS (* Function not implemented *)
| EUNKNOWNERR
Raised by the system calls below when an error is encountered. The rst component is the
error code; the second component is the function name; the third component is the string
parameter to the function, if it has one, or the empty string otherwise.
value error_message : error -> string
Return the process environment, as an array of strings with the format \variable=value".
See also sys__getenv.
174
Process handling
type process_status =
WEXITED of int
| WSIGNALED of int * bool
| WSTOPPED of int
The termination status of a process. WEXITED means that the process terminated normally
by exit; the argument is the return code. WSIGNALED means that the process was killed by
a signal; the rst argument is the signal number, the second argument indicates whether a
\core dump" was performed. WSTOPPED means that the process was stopped by a signal; the
argument is the signal number.
type wait_flag =
WNOHANG
| WUNTRACED
Flags for waitopt and waitpid. WNOHANG means do not block if no child has died yet, but
immediately return with a pid equal to 0. WUNTRACED means report also the children that
receive stop signals.
value execv : string -> string vect -> unit
execv prog args execute the program in le prog, with the arguments args, and the
current process environment.
value execve : string -> string vect -> string vect -> unit
Same as execv, except that the third argument provides the environment to the program
executed.
value execvp : string -> string vect -> unit
Fork a new process. The returned integer is 0 for the child process, the pid of the child
process for the parent process.
value wait : unit -> int * process_status
Wait until one of the children processes die, and return its pid and termination status.
value waitopt : wait_flag list -> int * process_status
Same as wait, but takes a list of options to avoid blocking, or also report stopped children.
The pid returned is 0 if no child has changed status.
value waitpid : wait_flag list -> int -> int * process_status
Same as waitopt, but waits for the process whose pid is given. Negative pid arguments
represent process groups.
Chapter 16. The unix library: Unix system calls 175
value system : string -> process_status
Execute the given command, wait until it terminates, and return its termination status.
The string is interpreted by the shell /bin/sh and therefore can contain redirections,
quotes, variables, etc. The result WEXITED 127 indicates that the shell couldn't be executed.
value getpid : unit -> int
Change the process priority. The integer argument is added to the \nice" value. (Higher
values of the \nice" value mean lower priorities.) Return the new nice value.
Basic le input/output
type file_descr
File descriptors for standard input, standard output and standard error.
type open_flag =
O_RDONLY (* Open for reading *)
| O_WRONLY (* Open for writing *)
| O_RDWR (* Open for reading and writing *)
| O_NDELAY (* Open in non-blocking mode *)
| O_APPEND (* Open for append *)
| O_CREAT (* Create if nonexistent *)
| O_TRUNC (* Truncate to 0 length if existing *)
| O_EXCL (* Fail if existing *)
Open the named le with the given
ags. Third argument is the permissions to give to the
le if it is created. Return a le descriptor on the named le.
176
value close : file_descr -> unit
Close a le descriptor.
value read : file_descr -> string -> int -> int -> int
read fd buff start len reads len characters from descriptor fd, storing them in string
buff, starting at position ofs in string buff. Return the number of characters actually read.
value write : file_descr -> string -> int -> int -> int
write fd buff start len writes len characters to descriptor fd, taking them from string
buff, starting at position ofs in string buff. Return the number of characters actually
written.
Positioning modes for lseek. SEEK_SET indicates positions relative to the beginning of the
le, SEEK_CUR relative to the current position, SEEK_END relative to the end of the le.
value lseek : file_descr -> int -> seek_command -> int
Same as stat, but in case the le is a symbolic link, return the information for the link itself.
value fstat : file_descr -> stats
Return the information for the le associated with the given descriptor.
Operations on le names
value unlink : string -> unit
link source dest creates a hard link named dest to the le named new.
178
File permissions and ownership
type access_permission =
R_OK (* Read permission *)
| W_OK (* Write permission *)
| X_OK (* Execution permission *)
| F_OK (* File exists *)
Change the owner uid and owner gid of the named le.
value fchown : file_descr -> int -> int -> unit
Set the process creation mask, and return the previous mask.
value access : string -> access_permission list -> unit
Check that the process has the given permissions over the named le. Raise Unix_error
otherwise.
Interface to fcntl in the case where the argument is an integer. The rst integer argument
is the command code; the second is the integer parameter.
value fcntl_ptr : file_descr -> int -> string -> int
Interface to fcntl in the case where the argument is a pointer. The integer argument is the
command code. A pointer to the string argument is passed as argument to the command.
Chapter 16. The unix library: Unix system calls 179
Directories
value mkdir : string -> file_perm -> unit
Return the next entry in a directory. Raise End_of_file when the end of the directory has
been reached.
value rewinddir : dir_handle -> unit
Create a pipe. The rst component of the result is opened for reading, that's the exit to the
pipe. The second component is opened for writing, that's the entrace to the pipe.
value dup : file_descr -> file_descr
Duplicate a descriptor.
value dup2 : file_descr -> file_descr -> unit
dup2 fd1 fd2 duplicates fd1 to fd2, closing fd2 if already opened.
180
value open_process_in: string -> in_channel
value open_process_out: string -> out_channel
value open_process: string -> in_channel * out_channel
High-level pipe and process management. These functions run the given command in
parallel with the program, and return channels connected to the standard input and/or the
standard output of the command. The command is interpreted by the shell /bin/sh (cf.
system). Warning: writes on channels are buered, hence be careful to call flush at the
right times to ensure correct synchronization.
value close_process_in: in_channel -> process_status
value close_process_out: out_channel -> process_status
value close_process: in_channel * out_channel -> process_status
Symbolic links
value symlink : string -> string -> unit
symlink source dest creates the le dest as a symbolic link to the le source.
value readlink : string -> string
Named pipes
value mkfifo : string -> file_perm -> unit
Special les
value ioctl_int : file_descr -> int -> int -> int
Interface to ioctl in the case where the argument is an integer. The rst integer argument
is the command code; the second is the integer parameter.
value ioctl_ptr : file_descr -> int -> string -> int
Interface to ioctl in the case where the argument is a pointer. The integer argument is the
command code. A pointer to the string argument is passed as argument to the command.
Chapter 16. The unix library: Unix system calls 181
Polling
value 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 (rst argument), for
writing (second argument), or for exceptional conditions (third argument). The fourth
argument is the maximal timeout, in seconds; a negative fourth argument means no timeout
(unbounded wait). The result is composed of three sets of descriptors: those ready for
reading (rst component), ready for writing (second component), and over which an
exceptional condition is pending (third component).
Locking
type lock_command =
F_ULOCK (* Unlock a region *)
| F_LOCK (* Lock a region, and block if already locked *)
| F_TLOCK (* Lock a region, or fail if already locked *)
| F_TEST (* Test a region for other process' locks *)
lockf fd cmd size puts a lock on a region of the le opened as fd. The region starts at the
current read/write position for fd (as set by lseek), and extends size bytes forward if size
is positive, size bytes backwards if size is negative, or to the end of the le if size is zero.
Signals
type signal =
SIGHUP (* hangup *)
| SIGINT (* interrupt *)
| SIGQUIT (* quit *)
| SIGILL (* illegal instruction (not reset when caught) *)
| SIGTRAP (* trace trap (not reset when caught) *)
| SIGABRT (* used by abort *)
| SIGEMT (* EMT instruction *)
| SIGFPE (* floating point exception *)
| SIGKILL (* kill (cannot be caught or ignored) *)
| SIGBUS (* bus error *)
| SIGSEGV (* segmentation violation *)
| SIGSYS (* bad argument to system call *)
| SIGPIPE (* write on a pipe with no one to read it *)
182
| SIGALRM (* alarm clock *)
| SIGTERM (* software termination signal from kill *)
| SIGURG (* urgent condition on IO channel *)
| SIGSTOP (* sendable stop signal not from tty *)
| SIGTSTP (* stop signal from tty *)
| SIGCONT (* continue a stopped process *)
| SIGCHLD (* to parent on child stop or exit *)
| SIGIO (* input/output possible signal *)
| SIGXCPU (* exceeded CPU time limit *)
| SIGXFSZ (* exceeded file size limit *)
| SIGVTALRM (* virtual time alarm *)
| SIGPROF (* profiling time alarm *)
| SIGWINCH (* window changed *)
| SIGLOST (* resource lost (eg, record-lock lost) *)
| SIGUSR1 (* user defined signal 1 *)
| SIGUSR2 (* user defined signal 2 *)
Time functions
type process_times =
{ tms_utime : float; (* User time for the process *)
tms_stime : float; (* System time for the process *)
tms_cutime : float; (* User time for the children processes *)
tms_cstime : float } (* System time for the children processes *)
Return the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds.
value gettimeofday : unit -> float
Convert a time in seconds, as returned by time, into a date and a time. Assumes Greenwich
meridian time zone.
value localtime : int -> tm
Convert a time in seconds, as returned by time, into a date and a time. Assumes the local
time zone.
value alarm : int -> int
Set the last access time (second arg) and last modication time (third arg) for a le. Times
are expressed in seconds from 00:00:00 GMT, Jan. 1, 1970.
184
User id, group id
value getuid : unit -> int
Set the real user id and eective user id for the process.
value getgid : unit -> int
Set the real group id and eective group id for the process.
value getgroups : unit -> int vect
Return the list of groups to which the user executing the process belongs.
type passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string }
Find an entry in passwd with the given user id, or raise Not_found.
value getgrgid : int -> group_entry
Find an entry in group with the given group id, or raise Not_found.
Internet addresses
type inet_addr
Conversions between string with the format XXX.YYY.ZZZ.TTT and Internet addresses.
inet_addr_of_string raises Failure when given a string that does not match this format.
Sockets
type socket_domain =
PF_UNIX (* Unix domain *)
| PF_INET (* Internet domain *)
The type of socket addresses. ADDR_UNIX name is a socket address in the Unix domain; name
is a le name in the le 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.
186
type shutdown_command =
SHUTDOWN_RECEIVE (* Close for receiving *)
| SHUTDOWN_SEND (* Close for sending *)
| SHUTDOWN_ALL (* Close both *)
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.
value socketpair :
socket_domain -> socket_type -> int -> file_descr * file_descr
Accept connections on the given socket. The returned descriptor is a socket connected to
the client; the returned address is the address of the connecting client.
value bind : file_descr -> sockaddr -> unit
Set up a socket for receiving connection requests. The integer argument is the maximal
number of pending requests.
value shutdown : file_descr -> shutdown_command -> unit
Connect to a server at the given address. Return a pair of buered channels connected to
the server. Remember to call flush on the output channel at the right times to ensure
correct synchronization.
value shutdown_connection : in_channel -> unit
Establish a server on the given address. The function given as rst argument is called for
each connection with two buered channels connected to the client. A new process is
created for each connection. The function establish_server never returns normally.
Find an entry in protocols with the given protocol number, or raise Not_found.
value getservbyname : string -> string -> service_entry
Find an entry in services with the given service number, or raise Not_found.
Terminal interface
The following functions implement the POSIX standard terminal interface. They provide
control over asynchronous communication ports and pseudo-terminals. Refer to the
termios man page for a complete description.
type terminal_io = {
Input modes:
Chapter 16. The unix library: Unix system calls 189
mutable c_ignbrk: bool; (* Ignore the break condition. *)
mutable c_brkint: bool; (* Signal interrupt on break condition. *)
mutable c_ignpar: bool; (* Ignore characters with parity errors. *)
mutable c_parmrk: bool; (* Mark parity errors. *)
mutable c_inpck: bool; (* Enable parity check on input. *)
mutable c_istrip: bool; (* Strip 8th bit on input characters. *)
mutable c_inlcr: bool; (* Map NL to CR on input. *)
mutable c_igncr: bool; (* Ignore CR on input. *)
mutable c_icrnl: bool; (* Map CR to NL on input. *)
mutable c_ixon: bool; (* Recognize XON/XOFF characters on input. *)
mutable c_ixoff: bool; (* Emit XON/XOFF chars to control input flow. *)
Output modes:
mutable c_opost: bool; (* Enable output processing. *)
Control modes:
mutable c_obaud: int; (* Output baud rate (0 means close connection).*)
mutable c_ibaud: int; (* Input baud rate. *)
mutable c_csize: int; (* Number of bits per character (5-8). *)
mutable c_cstopb: int; (* Number of stop bits (1-2). *)
mutable c_cread: bool; (* Reception is enabled. *)
mutable c_parenb: bool; (* Enable parity generation and detection. *)
mutable c_parodd: bool; (* Specify odd parity instead of even. *)
mutable c_hupcl: bool; (* Hang up on last close. *)
mutable c_clocal: bool; (* Ignore modem status lines. *)
Local modes:
mutable c_isig: bool; (* Generate signal on INTR, QUIT, SUSP. *)
mutable c_icanon: bool; (* Enable canonical processing
(line buffering and editing) *)
mutable c_noflsh: bool; (* Disable flush after INTR, QUIT, SUSP. *)
mutable c_echo: bool; (* Echo input characters. *)
mutable c_echoe: bool; (* Echo ERASE (to erase previous character). *)
mutable c_echok: bool; (* Echo KILL (to erase the current line). *)
mutable c_echonl: bool; (* Echo NL even if c_echo is not set. *)
Control characters:
mutable c_vintr: char; (* Interrupt character (usually ctrl-C). *)
mutable c_vquit: char; (* Quit character (usually ctrl-\). *)
mutable c_verase: char; (* Erase character (usually DEL or ctrl-H). *)
mutable c_vkill: char; (* Kill line character (usually ctrl-U). *)
mutable c_veof: char; (* End-of-file character (usually ctrl-D). *)
mutable c_veol: char; (* Alternate end-of-line char. (usually none). *)
mutable c_vmin: int; (* Minimum number of characters to read
190
before the read request is satisfied. *)
mutable c_vtime: int; (* Maximum read wait (in 0.1s units). *)
mutable c_vstart: char; (* Start character (usually ctrl-Q). *)
mutable c_vstop: char (* Stop character (usually ctrl-S). *)
}
value tcgetattr: file_descr -> terminal_io
Set the status of the terminal referred to by the given le descriptor. The second argument
indicates when the status change takes place: immediately (TCSANOW), when all pending
output has been transmitted (TCSADRAIN), or after
ushing all input that has been received
but not read (TCSAFLUSH). TCSADRAIN is recommended when changing the output
parameters; TCSAFLUSH, when changing the input parameters.
value tcsendbreak: file_descr -> int -> unit
Send a break condition on the given le descriptor. The second argument is the duration of
the break, in 0.1s units; 0 means standard duration (0.25s).
value tcdrain: file_descr -> unit
Waits until all output written on the given le descriptor has been transmitted.
type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
value tcflush: file_descr -> flush_queue -> unit
Discard data written on the given le descriptor but not yet transmitted, or data received
but not yet read, depending on the second argument: TCIFLUSH
ushes data received but
not read, TCOFLUSH
ushes data written but not transmitted, and TCIOFLUSH
ushes both.
type flow_action = TCOOFF | TCOON | TCIOFF | TCION
value tcflow: file_descr -> flow_action -> unit
191
192
Arithmetic operations
value prefix +/ : num -> num -> num
value add_num : num -> num -> num
Addition
value minus_num : num -> num
Unary negation.
value prefix -/ : num -> num -> num
value sub_num : num -> num -> num
Subtraction
value prefix */ : num -> num -> num
value mult_num : num -> num -> num
Multiplication
value square_num : num -> num
Squaring
value prefix // : num -> num -> num
value div_num : num -> num -> num
Division
value quo_num : num -> num -> num
value mod_num : num -> num -> num
Exponentiation
value is_integer_num : num -> bool
Return -1, 0 or 1 if the rst argument is less than, equal to, or greater than the second
argument.
value max_num : num -> num -> num
value min_num : num -> num -> num
Absolute value.
value succ_num: num -> num
succ n is n+1
value pred_num: num -> num
pred n is n-1
value incr_num: num ref -> unit
Approximate a number by a decimal. The rst argument is the required precision. The
second argument is the number to approximate. approx_fix uses decimal notation; the rst
argument is the number of digits after the decimal point. approx_exp uses scientic
(exponential) notation; the rst argument is the number of digits in the mantissa.
value num_of_string : string -> num
Get or set the
ag null_denominator. When on, attempting to create a rational with a
null denominator raises an exception. When o, rationals with null denominators are
accepted. Initially: on.
Chapter 17. The num library: arbitrary-precision rational arithmetic 195
value get_normalize_ratio : unit -> bool
value set_normalize_ratio : bool -> unit
Get or set the
ag normalize_ratio. When on, rational numbers are normalized after each
operation. When o, rational numbers are not normalized until printed. Initially: o.
value get_normalize_ratio_when_printing : unit -> bool
value set_normalize_ratio_when_printing : bool -> unit
Get or set the
ag approx_printing. When on, rational numbers are printed as a decimal
approximation. When o, rational numbers are printed as a fraction. Initially: o.
value get_floating_precision : unit -> int
value set_floating_precision : int -> unit
Get or set the parameter floating_precision. This parameter is the number of digits
displayed when approx_printing is on. Initially: 12.
196
Chapter 18
Compile a regular expression. The syntax for regular expressions is the same as in Gnu
Emacs. The special characters are \$^.*+?[]. The following constructs are recognized:
. matches any character except newline
* (postx) matches the previous expression zero, one or several times
+ (postx) matches the previous expression one or several times
? (postx) matches the previous expression once or not at all
[..] character set; ranges are denoted with -, as in a-z; an initial ^, as in ^0-9,
complements the set
197
198
^ matches at beginning of line
$ matches at end of line
\| (inx) alternative between two expressions
\(..\) grouping and naming of the enclosed expression
\1 the text matched by the rst \(...\) expression (\2 for the second expression, etc)
\b matches word boundaries
\ quotes special characters.
value regexp_case_fold: string -> regexp
Same as regexp, but the compiled expression will match text in a case-insensitive way:
uppercase and lowercase letters will be considered equivalent.
search_forward r s start searchs the string s for a substring matching the regular
expression r. The search starts at position start and proceeds towards the end of the
string. Return the position of the rst character of the matched substring, or raise
Not_found if no substring matches.
value search_backward: regexp -> string -> int -> int
Same as search_forward, but the search proceeds towards the beginning of the string.
value matched_string: string -> string
match_beginning() returns the position of the rst character of the substring that was
matched by string_match, search_forward or search_backward. match_end() returns
the position of the character following the last character of the matched substring.
value matched_group: int -> string -> string
matched_group n s returns the substring of s that was matched by the nth group \(...\)
of the regular expression during the latest string_match, search_forward or
search_backward. The user must make sure that the parameter s is the same string that
was passed to the matching or searching function.
Chapter 18. The str library: regular expressions and string processing 199
value group_beginning: int -> int
value group_end: int -> int
group_beginning n returns the position of the rst character of the substring that was
matched by the nth group of the regular expression. group_end n returns the position of
the character following the last character of the matched substring.
Replacement
value global_replace: regexp -> string -> string -> string
global_replace regexp repl s returns a string identical to s, except that all substrings
of s that match regexp have been replaced by repl. The replacement text repl can contain
\1, \2, etc; these sequences will be replaced by the text matched by the corresponding group
in the regular expression. \0 stands for the text matched by the whole regular expression.
value replace_first: regexp -> string -> string -> string
Same as global_replace, except that only the rst substring matching the regular
expression is replaced.
value global_substitute: regexp -> (string -> string) -> string -> string
Same as global_substitute, except that only the rst substring matching the regular
expression is replaced.
Splitting
value 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.
value bounded_split: regexp -> string -> int -> string list
Same as split, but splits into at most n substrings, where n is the extra integer parameter.
200
Joining
value concat: string list -> string
Catenate a list of string. The rst argument is a separator, which is inserted between the
strings.
Extracting substrings
value string_before: string -> int -> string
Formatting
value format: ('a, unit, string) printf__format -> 'a
Same as printf__sprintf.
Part V
Appendix
201
Chapter 19
Further reading
For the interested reader, we list below some references to books and reports related (sometimes
loosely) to Caml Light.
19.1 Programming in ML
The books below are programming courses taught in ML. Their main goal is to teach programming,
not to describe ML in full details | though most contain fairly good introductions to the ML
language. Some of those books use the Standard ML dialect instead of the Caml dialect, so you
will have to keep in mind the dierences in syntax and in semantics.
Pierre Weis and Xavier Leroy. Le langage Caml. InterE ditions, 1993.
The natural companion to this manual, provided you read French. This book is a step-by-
step introduction to programming in Caml, and presents many realistic examples of Caml
programs.
Guy Cousineau and Michel Mauny. Approche fonctionnelle de la programmation. Ediscience,
1995.
Another Caml programming course written in French, with many original examples.
Lawrence C. Paulson. ML for the working programmer. Cambridge University Press, 1991.
A good introduction to programming in Standard ML. Develops a theorem prover as a com-
plete example. Contains a presentation of the module system of Standard ML.
Jerey D. Ullman. Elements of ML programming. Prentice Hall, 1993.
Another good introduction to programming in Standard ML. No realistic examples, but a
very detailed presentation of the language constructs.
Ryan Stansifer. ML primer. Prentice-Hall, 1992.
A short, but nice introduction to programming in Standard ML.
Therese Accart Hardin and Veronique Donzeau-Gouge Viguie. Concepts et outils de la pro-
grammation. Du fonctionnel a l'imperatif avec Caml et Ada. InterE ditions, 1992.
203
204
A rst course in programming, that rst introduces the main programming notions in Caml,
then shows them underlying Ada. Intended for beginners; slow-paced for the others.
Rachel Harrison. Abstract Data Types in Standard ML. John Wiley & Sons, 1993.
A presentation of Standard ML from the standpoint of abstract data types. Uses intensively
the Standard ML module system.
Harold Abelson and Gerald Jay Sussman. Structure and Interpretation of Computer Pro-
grams. The MIT press, 1985. (French translation: Structure et interpretation des programmes
informatiques, InterE ditions, 1989.)
An outstanding course on programming, taught in Scheme, the modern dialect of Lisp. Well
worth reading, even if you are more interested in ML than in Lisp.
207
208
blit_vect, 135 cos, 118
blue, 165 cosh, 118
bool (module), 113 create_image, 168
bounded_split, 199 create_lexer, 152
Break (exception), 161 create_lexer_channel, 152
builtin (module), 114 create_lexer_string, 152
button_down, 169 create_string, 132
current_dir_name, 140
catch_break, 161 current_point, 166
cd, 57 cyan, 165
ceil, 118
ceiling_num, 192 debug_mode, 57
char (module), 115 decr, 130
char_for_read, 115 decr_num, 193
char_of_int, 115 denominator_num, 191
chdir, 161, 179 descr_of_in_channel, 176
check_suffix, 140 descr_of_out_channel, 176
chmod, 178 diff, 158
choose, 158 directory, 57
chop_suffix, 140 dirname, 140
chown, 178 div_float, 117
clear, 150, 156, 159 div_int, 120
clear_graph, 165 div_num, 192
clear_parser, 154 Division_by_zero (exception), 120
close, 161, 176 do_list, 128
close_box, 141 do_list2, 128
close_graph, 164 do_list_combine, 130
close_in, 127 do_stream, 131
close_out, 125 do_table, 151
close_process, 180 do_table_rev, 151
close_process_in, 180 do_vect, 135
close_process_out, 180 draw_arc, 166
close_tbox, 144 draw_char, 166
closedir, 179 draw_circle, 166
combine, 130 draw_ellipse, 166
command_line, 160 draw_image, 167
compare, 115, 139, 158 draw_string, 166
compare_num, 193 dump_image, 167
compare_strings, 133 dup, 179
compile, 56 dup2, 179
concat, 132, 140, 200
concat_vect, 134 elements, 158
connect, 186 empty, 153, 157
contains, 139 Empty (exception), 156, 159
copy_vect, 134 End_of_file (exception), 122
end_of_stream, 131
Index to the library 209
environment, 173 float_of_num, 194
eprint, 155 float_of_string, 119
eprintf, 147, 155 floor, 118
eq (module), 115 floor_num, 192
eq_float, 118 flush, 124
eq_int, 120 fold, 158
eq_num, 193 for_all, 129
eq_string, 133 force_newline, 142
equal, 158 foreground, 165
err_formatter, 145 fork, 174
error_message, 173 format, 200
establish_server, 187 format (module), 140
exc (module), 116 fprint, 155
except, 129 fprintf, 146, 154
exceptq, 129 frexp, 119
execv, 174 fst, 130
execve, 174 fstat, 177
execvp, 174 fstring (module), 119
exists, 129 ftruncate, 176
exit, 122, 160 full_init, 157
Exit (exception), 116 full_major, 149
exp, 118 fvect (module), 119
umask, 178
union, 129, 158
unix (module), 171
Unix_error (exception), 173
unlink, 177
untrace, 57
utimes, 183
wait, 174
wait_next_event, 168
waitopt, 174
waitpid, 174
white, 165
write, 176
yellow, 165
Index of keywords
and, see let, type, exception, value, where when, 36
as, 21 where, 37
while, 26
begin, 22, 23 with, see match, try
else, see if
end, 22, 23
exception, 31, 32
for, 22, 26
fun, 22
function, 22, 35
if, 22, 25
in, see let
let, 22, 24
match, 22, 26, 35
mutable, 30, 37
not, 22
of, see type, exception
or, 22, 26
prefix, 22, 28, 39
rec, see let, where
then, see if
to, see for
try, 22, 27
type, 30, 32
value, 32
216