The OCaml system release 5.0 Documentation and user’s manual Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy, KC Sivaramakrishnan and Jérôme Vouillon December 20, 2022 Copyright © 2022 Institut National de Recherche en Informatique et en Automatique Contents I An introduction to OCaml 13 1 The core language 15 1.3 Functions as values .4 Records and variants .8 Symbolic processing of expressions .11 Standalone OCaml programs. 33 2 The module system 35 2.4 Functors and type abstraction .5 Modules and separate compilation. 44 3 Objects in OCaml 47 3.1 Classes and objects .3 Reference to self .2 Labels and type inference .3 Suggestions for labeling .3 Weaknesses of polymorphic variants. 88 6 Polymorphism and its limitations 89 6.1 Weak polymorphism and mutation .3 Higher-rank polymorphic functions.
97 7 Generalized algebraic datatypes 99 7.5 Existential type names in error messages .6 Explicit naming of existentials .7 Equations on non-local abstract types. 104 8 Advanced examples with classes and modules 105 8.1 Extended example: bank accounts .2 Simple modules as classes .3 The subject/observer pattern .2 Domainslib: A library for nested-parallel programming .3 Parallel garbage collection .4 Memory model: The easy bits .6 Interaction with C bindings. 132 3 10 Memory model: The hard bits 135 10.1 Why weakly consistent memory? .2 Data race freedom implies sequential consistency .3 Reasoning with DRF-SC .4 Local data race freedom .5 An operational view of the memory model .6 Non-compliant operations. 147 II The OCaml language 149 11 The OCaml language 151 11.8 Type and exception definitions .1 Recursive definitions of values .4 Locally abstract types .5 First-class modules .6 Recovering the type of a module .7 Substituting inside a signature .8 Type-level module aliases .9 Overriding in open statements .10 Generalized algebraic datatypes .11 Syntax for Bigarray access .14 Extensible variant types .16 Extension-only syntax .19 Extended indexing operators .20 Empty variant types .22 Generalized open statements.
254 III The OCaml tools 269 13 Batch compilation (ocamlc) 271 13.1 Overview of the compiler .3 Modules and the file system. 290 14 The toplevel system or REPL (ocaml) 295 14.3 The toplevel and the module system .5 Building custom toplevel systems: ocamlmktop .6 The native toplevel: ocamlnat (experimental). 310 15 The runtime system (ocamlrun) 311 15.3 Dynamic loading of shared libraries. 315 16 Native-code compilation (ocamlopt) 317 16.1 Overview of the compiler .4 Running executables produced by ocamlopt .5 Compatibility with the bytecode compiler.
334 17 Lexer and parser generators (ocamllex, ocamlyacc) 335 17.1 Overview of ocamllex .2 Syntax of lexer definitions .3 Overview of ocamlyacc .4 Syntax of grammar definitions. 351 19 The documentation generator (ocamldoc) 355 19.2 Syntax of documentation comments .4 Adding command line options .1 Compiling for debugging .6 The call stack .7 Examining variable values .8 Controlling the debugger .10 Running the debugger under Emacs .1 Compiling for profiling .2 Profiling an execution .3 Printing profiling information. 393 22 Interfacing C with OCaml 395 22.1 Overview and compilation information .2 The value type .3 Representation of OCaml data types .4 Operations on values .5 Living in harmony with the garbage collector .7 Advanced topic: callbacks from C to OCaml .8 Advanced example with callbacks .9 Advanced topic: custom blocks .10 Advanced topic: Bigarrays and the OCaml-C interface .11 Advanced topic: cheaper C call .12 Advanced topic: multithreading .13 Advanced topic: interfacing with Windows Unicode APIs .14 Building mixed C/OCaml libraries: ocamlmklib .15 Cautionary words: the internal runtime API. 441 6 23 Optimisation with Flambda 443 23.2 Command-line flags .5 Default settings of parameters .6 Manual control of inlining and specialisation .8 Other code motion transformations .10 Removal of unused code and values .11 Other code transformations .12 Treatment of effects .13 Compilation of statically-allocated modules .14 Inhibition of optimisation .15 Use of unsafe operations.
465 24 Fuzzing with afl-fuzz 467 24. 467 25 Runtime tracing with runtime events 469 25. 471 26 The “Tail Modulo Constructor” program transformation 475 26.2 Danger: getting out of tail-mod-cons .3 Details on the transformation. 483 IV The OCaml library 487 27 The core library 489 27.1 Built-in types and predefined exceptions .2 Module Stdlib : The OCaml Standard library.
492 28 The standard library 521 28.1 Module Arg : Parsing of command line arguments.2 Module Array : Array operations.3 Module ArrayLabels : Array operations.4 Module Atomic : Atomic references.5 Module Bigarray : Large, multi-dimensional, numerical arrays.6 Module Bool : Boolean values.7 Module Buffer : Extensible buffers.8 Module Bytes : Byte sequence operations.9 Module BytesLabels : Byte sequence operations.10 Module Callback : Registering OCaml values with the C runtime.11 Module Char : Character operations.12 Module Complex : Complex numbers.13 Module Condition : Condition variables.15 Module Digest : MD5 message digest.17 Module Either : Either type.18 Module Ephemeron : Ephemerons and weak hash tables.19 Module Filename : Operations on file names.20 Module Float : Floating-point arithmetic.21 Module Format : Pretty-printing.22 Module Fun : Function manipulation.23 Module Gc : Memory management control and statistics; finalised values.24 Module Hashtbl : Hash tables and hash functions.25 Module In_channel : Input channels.26 Module Int : Integer values.27 Module Int32 : 32-bit integers.28 Module Int64 : 64-bit integers.29 Module Lazy : Deferred computations.30 Module Lexing : The run-time library for lexers generated by ocamllex.31 Module List : List operations.32 Module ListLabels : List operations.33 Module Map : Association tables over ordered types.34 Module Marshal : Marshaling of data structures.35 Module MoreLabels : Extra labeled libraries.36 Module Mutex : Locks for mutual exclusion.37 Module Nativeint : Processor-native integers.38 Module Oo : Operations on objects .39 Module Option : Option values.40 Module Out_channel : Output channels.41 Module Parsing : The run-time library for parsers generated by ocamlyacc.42 Module Printexc : Facilities for printing exceptions and inspecting current call stack.43 Module Printf : Formatted output functions.44 Module Queue : First-in first-out queues.45 Module Random : Pseudo-random number generators (PRNG).46 Module Result : Result values.47 Module Runtime_events : Runtime events - ring buffer-based runtime tracing .48 Module Scanf : Formatted input functions.49 Module Seq : Sequences.50 Module Set : Sets over ordered types.51 Module Semaphore : Semaphores .52 Module Stack : Last-in first-out stacks.53 Module StdLabels : Standard labeled libraries.54 Module String : Strings.55 Module StringLabels : Strings.56 Module Sys : System interface.57 Module Uchar : Unicode characters.58 Module Unit : Unit values.59 Module Weak : Arrays of weak pointers and hash sets of weak pointers.60 Ocaml_operators : Precedence level and associativity of operators. 852 29 The compiler front-end 855 29.1 Module Ast_mapper : The interface of a -ppx rewriter .2 Module Asttypes : Auxiliary AST types used by parsetree and typedtree.3 Module Location : Source code locations (ranges of positions), used in parsetree.4 Module Longident : Long identifiers, used in parsetree.5 Module Parse : Entry points in the parser .6 Module Parsetree : Abstract syntax tree produced by parsing .7 Module Pprintast : Pretty-printers for Parsetree[29. 892 30 The unix library: Unix system calls 895 30.1 Module Unix : Interface to the Unix system.2 Module UnixLabels: labelized version of the interface. 938 31 The str library: regular expressions and string processing 941 31.1 Module Str : Regular expressions and high-level string processing.
941 32 The runtime_events library 949 32.1 Module Runtime_events : Runtime events - ring buffer-based runtime tracing. 949 33 The threads library 955 33.1 Module Thread : Lightweight threads for Posix 1003.2 Module Event : First-class synchronous communication. 958 34 The dynlink library: dynamic loading and linking of object files 961 34.1 Module Dynlink : Dynamic loading of. 961 35 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk) 965 35.1 The Graphics Library .2 The Bigarray Library .3 The Num Library .4 The Labltk Library and OCamlBrowser.
966 9 V Indexes 967 Index to the library 969 Index of keywords 989 Foreword This manual documents the release 5.0 of the OCaml system. It is organized as follows. • Part I, “An introduction to OCaml”, gives an overview of the language. • Part II, “The OCaml language”, is the reference description of the language.
• Part III, “The OCaml tools”, documents the compilers, toplevel system, and programming utilities. • Part IV, “The OCaml library”, describes the modules provided in the standard library. • Part V, “Indexes”, contains an index of all identifiers defined in the standard library, and an index of keywords. Conventions OCaml runs on several operating systems.
The parts of this manual that are specific to one operating system are presented as shown below: Unix: This is material specific to the Unix family of operating systems, including Linux and macOS. Windows: This is material specific to Microsoft Windows (Vista, 7, 8, 10). License The OCaml system is copyright © 1996–2022 Institut National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership rights to the OCaml system.
The OCaml system is open source and can be freely redistributed. See the file LICENSE in the distribution for licensing information. The OCaml documentation and user’s manual is copyright © 2022 Institut National de Recherche en Informatique et en Automatique (INRIA). The OCaml documentation and user’s manual is licensed under a Creative Commons Attribution- ShareAlike 4.0 International License (CC BY-SA 4.org/licenses/ by-sa/4.
11 12 Foreword Availability The complete OCaml distribution can be accessed via the website https://ocaml. This site contains a lot of additional information on OCaml. Part I An introduction to OCaml 13 Chapter 1 The core language This part of the manual is a tutorial introduction to the OCaml language. A good familiarity with programming in a conventional languages (say, C or Java) is assumed, but no prior exposure to functional languages is required.
The present chapter introduces the core language. Chapter 2 deals with the module system, chapter 3 with the object-oriented features, chapter 4 with labeled arguments, chapter 5 with polymorphic variants, chapter 6 with the limitations of polymorphism, and chapter 8 gives some advanced examples.1 Basics For this overview of OCaml, we use the interactive system, which is started by running ocaml from the Unix shell or Windows command prompt. This tutorial is presented as the transcript of a session with the interactive system: lines starting with # represent user input; the system responses are printed below, without a leading #. Under the interactive system, the user types OCaml phrases terminated by ;; in response to the # prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation.
Phrases are either simple expressions, or let definitions of identifiers (either values or functions). # 1 + 2 * 3;; - : int = 7 # let pi = 4.0;; val pi : float = 3. x;; val square : float -> float = <fun> # square (sin pi) +. The OCaml system computes both the value and the type for each phrase.
Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: + and * operate on integers, but +. operate on floats.0 * 2;; Error : This expression has type float but an expression was expected of type int Recursive functions are defined with the let rec binding: # let rec fib n = if n < 2 then n else fib (n - 1) + fib (n - 2);; val fib : int -> int = <fun> # fib 10;; - : int = 55 1.