Dataset Viewer
Auto-converted to Parquet
text
stringlengths
10
16.2k
# OCaml - The OCaml Manual Source: https://ocaml.org/manual/5.2/manual001.html ☰
# The OCaml system  release 5.2
### February, ‍2024
# Contents [Home](index.html)[Foreword »](foreword.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The OCaml Manual Source: https://ocaml.org/manual/5.2/foreword.html ☰
# The OCaml system  release 5.2
### February, ‍2024
# Foreword - [Conventions](foreword.html#conventions) - [License](foreword.html#license) - [Availability](foreword.html#availability) This manual documents the release 5.2 of the OCaml system. It is organized as follows. - Part ‍[I](index.html#p%3Atutorials), “An introduction to OCaml”, gives an overview of the language. - Part ‍[II](index.html#p%3Arefman), “The OCaml language”, is the reference description of the language. - Part ‍[III](index.html#p%3Acommands), “The OCaml tools”, documents the compilers, toplevel system, and programming utilities. - Part ‍[IV](index.html#p%3Alibrary), “The OCaml library”, describes the modules provided in the standard library.
## 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, 11).
## License The OCaml system is copyright © 1996–2024 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 © 2024 Institut National de Recherche en Informatique et en Automatique (INRIA). [Creative Commons License](http://creativecommons.org/licenses/by-sa/4.0/) The OCaml documentation and user's manual is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). [Creative Commons License](https://creativecommons.org/publicdomain/zero/1.0/) The sample code in the user's manual and in the reference documentation of the standard library is licensed under a [Creative Commons CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License](https://creativecommons.org/publicdomain/zero/1.0/).
## Availability The complete OCaml distribution can be accessed via the [ocaml.org website](https://ocaml.org/). This site contains a lot of additional information on OCaml. [« Contents](manual001.html)[The core language »](coreexamples.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The core language Source: https://ocaml.org/manual/5.2/coreexamples.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [Polymorphism and its limitations](polymorphism.html) - [Generalized algebraic datatypes](gadts-tutorial.html) - [Advanced examples with classes and modules](advexamples.html) - [Parallel programming](parallelism.html) - [Memory model: The hard bits](memorymodel.html)
# 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](moduleexamples.html#c%3Amoduleexamples) deals with the module system, chapter ‍[3](objectexamples.html#c%3Aobjectexamples) with the object-oriented features, chapter ‍[4](lablexamples.html#c%3Alabl-examples) with labeled arguments, chapter ‍[5](polyvariant.html#c%3Apoly-variant) with polymorphic variants, chapter ‍[6](polymorphism.html#c%3Apolymorphism) with the limitations of polymorphism, and chapter ‍[8](advexamples.html#c%3Aadvexamples) 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). ```ocaml # 1 + 2 \* 3;; - : int = 7 # let pi = 4.0 \*. atan 1.0;; val pi : float = 3.14159265358979312 # let square x = x \*. x;; val square : float -> float = \<fun\> # square (sin pi) +. square (cos pi);; - : float = 1. ``` The 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 +. and \*. operate on floats. ```ocaml # 1.0 \* 2;; Error: This expression has type float but an expression was expected of type int ``` Recursive functions are defined with the let rec binding: ```ocaml # 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 ```
## 2 Data types In addition to integers and floating-point numbers, OCaml offers the usual basic data types: - booleans ```ocaml # (1 \< 2) = false;; - : bool = false # let one = if true then 1 else 2;; val one : int = 1 ``` - characters ```ocaml # 'a';; - : char = 'a' # int_of_char '\\n';; - : int = 10 ``` - immutable character strings ```ocaml # "Hello" ^ " " ^ "world";; - : string = "Hello world" # {\|This is a quoted string, here, neither \\ nor " are special characters\|};; - : string = "This is a quoted string, here, neither \\\\ nor \\" are special characters" # {\|"\\\\"\|}="\\"\\\\\\\\\\"";; - : bool = true # {delimiter\|the end of this\|}quoted string is here\|delimiter} = "the end of this\|}quoted string is here";; - : bool = true ``` Predefined data structures include tuples, arrays, and lists. There are also general mechanisms for defining your own data structures, such as records and variants, which will be covered in more detail later; for now, we concentrate on lists. Lists are either given in extension as a bracketed list of semicolon-separated elements, or built from the empty list \[\] (pronounce “nil”) by adding elements in front using the :: (“cons”) operator. ```ocaml # let l = \["is"; "a"; "tale"; "told"; "etc."\];; val l : string list = \["is"; "a"; "tale"; "told"; "etc."\] # "Life" :: l;; - : string list = \["Life"; "is"; "a"; "tale"; "told"; "etc."\] ```
## 2 Data types As with all other OCaml data structures, lists do not need to be explicitly allocated and deallocated from memory: all memory management is entirely automatic in OCaml. Similarly, there is no explicit handling of pointers: the OCaml compiler silently introduces pointers where necessary. As with most OCaml data structures, inspecting and destructuring lists is performed by pattern-matching. List patterns have exactly the same form as list expressions, with identifiers representing unspecified parts of the list. As an example, here is insertion sort on a list: ```ocaml # let rec sort lst = match lst with \[\] -> \[\] \| head :: tail -> insert head (sort tail) and insert elt lst = match lst with \[\] -> \[elt\] \| head :: tail -> if elt \<= head then elt :: lst else head :: insert elt tail ;; val sort : 'a list -> 'a list = \<fun\> val insert : 'a -> 'a list -> 'a list = \<fun\> # sort l;; - : string list = \["a"; "etc."; "is"; "tale"; "told"\] ``` The type inferred for sort, 'a list -> 'a list, means that sort can actually apply to lists of any type, and returns a list of the same type. The type 'a is a *type variable*, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, \<=, etc.) are *polymorphic* in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types. ```ocaml # sort \[6; 2; 5; 3\];; - : int list = \[2; 3; 5; 6\] # sort \[3.14; 2.718\];; - : float list = \[2.718; 3.14\] ```
## 2 Data types The sort function above does not modify its input list: it builds and returns a new list containing the same elements as the input list, in ascending order. There is actually no way in OCaml to modify a list in-place once it is built: we say that lists are *immutable* data structures. Most OCaml data structures are immutable, but a few (most notably arrays) are *mutable*, meaning that they can be modified in-place at any time. The OCaml notation for the type of a function with multiple arguments is arg1_type -> arg2_type -> ... -> return_type. For example, the type inferred for insert, 'a -> 'a list -> 'a list, means that insert takes two arguments, an element of any type 'a and a list with elements of the same type 'a and returns a list of the same type.
## 3 Functions as values OCaml is a functional language: functions in the full mathematical sense are supported and can be passed around freely just as any other piece of data. For instance, here is a deriv function that takes any float function as argument and returns an approximation of its derivative function: ```ocaml # let deriv f dx = fun x -> (f (x +. dx) -. f x) /. dx;; val deriv : (float -> float) -> float -> float -> float = \<fun\> # let sin' = deriv sin 1e-6;; val sin' : float -> float = \<fun\> # sin' pi;; - : float = -1.00000000013961143 ``` Even function composition is definable: ```ocaml # let compose f g = fun x -> f (g x);; val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = \<fun\> # let cos2 = compose square cos;; val cos2 : float -> float = \<fun\> ``` Functions that take other functions as arguments are called “functionals”, or “higher-order functions”. Functionals are especially useful to provide iterators or similar generic operations over a data structure. For instance, the standard OCaml library provides a List.map functional that applies a given function to each element of a list, and returns the list of the results: ```ocaml # List.map (fun n -> n \* 2 + 1) \[0;1;2;3;4\];; - : int list = \[1; 3; 5; 7; 9\] ``` This functional, along with a number of other list and array functionals, is predefined because it is often useful, but there is nothing magic with it: it can easily be defined as follows. ```ocaml # let rec map f l = match l with \[\] -> \[\] \| hd :: tl -> f hd :: map f tl;; val map : ('a -> 'b) -> 'a list -> 'b list = \<fun\> ```
## 4 Records and variants User-defined data structures include records and variants. Both are defined with the type declaration. Here, we declare a record type to represent rational numbers. ```ocaml # type ratio = {num: int; denom: int};; type ratio = { num : int; denom : int; } # let add_ratio r1 r2 = {num = r1.num \* r2.denom + r2.num \* r1.denom; denom = r1.denom \* r2.denom};; val add_ratio : ratio -> ratio -> ratio = \<fun\> # add_ratio {num=1; denom=3} {num=2; denom=5};; - : ratio = {num = 11; denom = 15} ``` Record fields can also be accessed through pattern-matching: ```ocaml # let integer_part r = match r with {num=num; denom=denom} -> num / denom;; val integer_part : ratio -> int = \<fun\> ``` Since there is only one case in this pattern matching, it is safe to expand directly the argument r in a record pattern: ```ocaml # let integer_part {num=num; denom=denom} = num / denom;; val integer_part : ratio -> int = \<fun\> ``` Unneeded fields can be omitted: ```ocaml # let get_denom {denom=denom} = denom;; val get_denom : ratio -> int = \<fun\> ``` Optionally, missing fields can be made explicit by ending the list of fields with a trailing wildcard \_:: ```ocaml # let get_num {num=num; \_ } = num;; val get_num : ratio -> int = \<fun\> ``` When both sides of the = sign are the same, it is possible to avoid repeating the field name by eliding the =field part: ```ocaml # let integer_part {num; denom} = num / denom;; val integer_part : ratio -> int = \<fun\> ``` This short notation for fields also works when constructing records:
## 4 Records and variants ```ocaml # let ratio num denom = {num; denom};; val ratio : int -> int -> ratio = \<fun\> ``` At last, it is possible to update few fields of a record at once: ```ocaml # let integer_product integer ratio = { ratio with num = integer \* ratio.num };; val integer_product : int -> ratio -> ratio = \<fun\> ``` With this functional update notation, the record on the left-hand side of with is copied except for the fields on the right-hand side which are updated. The declaration of a variant type lists all possible forms for values of that type. Each case is identified by a name, called a constructor, which serves both for constructing values of the variant type and inspecting them by pattern-matching. Constructor names are capitalized to distinguish them from variable names (which must start with a lowercase letter). For instance, here is a variant type for doing mixed arithmetic (integers and floats): ```ocaml # type number = Int of int \| Float of float \| Error;; type number = Int of int \| Float of float \| Error ``` This declaration expresses that a value of type number is either an integer, a floating-point number, or the constant Error representing the result of an invalid operation (e.g. a division by zero). Enumerated types are a special case of variant types, where all alternatives are constants: ```ocaml # type sign = Positive \| Negative;; type sign = Positive \| Negative # let sign_int n = if n \>= 0 then Positive else Negative;; val sign_int : int -> sign = \<fun\> ```
## 4 Records and variants To define arithmetic operations for the number type, we use pattern-matching on the two numbers involved: ```ocaml # let add_num n1 n2 = match (n1, n2) with (Int i1, Int i2) -> (\* Check for overflow of integer addition \*) if sign_int i1 = sign_int i2 && sign_int (i1 + i2) \<\> sign_int i1 then Float(float i1 +. float i2) else Int(i1 + i2) \| (Int i1, Float f2) -> Float(float i1 +. f2) \| (Float f1, Int i2) -> Float(f1 +. float i2) \| (Float f1, Float f2) -> Float(f1 +. f2) \| (Error, \_) -> Error \| (\_, Error) -> Error;; val add_num : number -> number -> number = \<fun\> # add_num (Int 123) (Float 3.14159);; - : number = Float 126.14159 ``` Another interesting example of variant type is the built-in 'a option type which represents either a value of type 'a or an absence of value: ```ocaml # type 'a option = Some of 'a \| None;; type 'a option = Some of 'a \| None ``` This type is particularly useful when defining function that can fail in common situations, for instance ```ocaml # let safe_square_root x = if x \>= 0. then Some(sqrt x) else None;; val safe_square_root : float -> float option = \<fun\> ``` The most common usage of variant types is to describe recursive data structures. Consider for example the type of binary trees: ```ocaml # type 'a btree = Empty \| Node of 'a \* 'a btree \* 'a btree;; type 'a btree = Empty \| Node of 'a \* 'a btree \* 'a btree ```
## 4 Records and variants This definition reads as follows: a binary tree containing values of type 'a (an arbitrary type) is either empty, or is a node containing one value of type 'a and two subtrees also containing values of type 'a, that is, two 'a btree. Operations on binary trees are naturally expressed as recursive functions following the same structure as the type definition itself. For instance, here are functions performing lookup and insertion in ordered binary trees (elements increase from left to right): ```ocaml # let rec member x btree = match btree with Empty -> false \| Node(y, left, right) -> if x = y then true else if x \< y then member x left else member x right;; val member : 'a -> 'a btree -> bool = \<fun\> # let rec insert x btree = match btree with Empty -> Node(x, Empty, Empty) \| Node(y, left, right) -> if x \<= y then Node(y, insert x left, right) else Node(y, left, insert x right);; val insert : 'a -> 'a btree -> 'a btree = \<fun\> ```
### 4.1 Record and variant disambiguation ( This subsection can be skipped on the first reading ) Astute readers may have wondered what happens when two or more record fields or constructors share the same name ```ocaml # type first_record = { x:int; y:int; z:int } type middle_record = { x:int; z:int } type last_record = { x:int };; # type first_variant = A \| B \| C type last_variant = A;; ``` The answer is that when confronted with multiple options, OCaml tries to use locally available information to disambiguate between the various fields and constructors. First, if the type of the record or variant is known, OCaml can pick unambiguously the corresponding field or constructor. For instance: ```ocaml # let look_at_x\_then_z (r:first_record) = let x = r.x in x + r.z;; val look_at_x\_then_z : first_record -> int = \<fun\> # let permute (x:first_variant) = match x with \| A -> (B:first_variant) \| B -> A \| C -> C;; val permute : first_variant -> first_variant = \<fun\> # type wrapped = First of first_record let f (First r) = r, r.x;; type wrapped = First of first_record val f : wrapped -> first_record \* int = \<fun\> ```
### 4.1 Record and variant disambiguation In the first example, (r:first_record) is an explicit annotation telling OCaml that the type of r is first_record. With this annotation, Ocaml knows that r.x refers to the x field of the first record type. Similarly, the type annotation in the second example makes it clear to OCaml that the constructors A, B and C come from the first variant type. Contrarily, in the last example, OCaml has inferred by itself that the type of r can only be first_record and there are no needs for explicit type annotations. Those explicit type annotations can in fact be used anywhere. Most of the time they are unnecessary, but they are useful to guide disambiguation, to debug unexpected type errors, or combined with some of the more advanced features of OCaml described in later chapters. Secondly, for records, OCaml can also deduce the right record type by looking at the whole set of fields used in a expression or pattern: ```ocaml # let project_and_rotate {x; y; \_} = { x= - y; y = x; z = 0} ;; val project_and_rotate : first_record -> first_record = \<fun\> ``` Since the fields x and y can only appear simultaneously in the first record type, OCaml infers that the type of project_and_rotate is first_record -> first_record. In last resort, if there is not enough information to disambiguate between different fields or constructors, Ocaml picks the last defined type amongst all locally valid choices: ```ocaml # let look_at_xz {x; z} = x;; val look_at_xz : middle_record -> int = \<fun\> ```
### 4.1 Record and variant disambiguation Here, OCaml has inferred that the possible choices for the type of {x;z} are first_record and middle_record, since the type last_record has no field z. Ocaml then picks the type middle_record as the last defined type between the two possibilities. Beware that this last resort disambiguation is local: once Ocaml has chosen a disambiguation, it sticks to this choice, even if it leads to an ulterior type error: ```ocaml # let look_at_x\_then_y r = let x = r.x in (\* Ocaml deduces \[r: last_record\] \*) x + r.y;; Error: This expression has type last_record There is no field y within type last_record # let is_a\_or_b x = match x with \| A -> true (\* OCaml infers \[x: last_variant\] \*) \| B -> true;; Error: This variant pattern is expected to have type last_variant There is no constructor B within type last_variant ``` Moreover, being the last defined type is a quite unstable position that may change surreptitiously after adding or moving around a type definition, or after opening a module (see chapter [2](moduleexamples.html#c%3Amoduleexamples)). Consequently, adding explicit type annotations to guide disambiguation is more robust than relying on the last defined type disambiguation.
## 5 Imperative features Though all examples so far were written in purely applicative style, OCaml is also equipped with full imperative features. This includes the usual while and for loops, as well as mutable data structures such as arrays. Arrays are either created by listing semicolon-separated element values between \[\| and \|\] brackets, or allocated and initialized with the Array.make function, then filled up later by assignments. For instance, the function below sums two vectors (represented as float arrays) componentwise. ```ocaml # let add_vect v1 v2 = let len = min (Array.length v1) (Array.length v2) in let res = Array.make len 0.0 in for i = 0 to len - 1 do res.(i) \<- v1.(i) +. v2.(i) done; res;; val add_vect : float array -> float array -> float array = \<fun\> # add_vect \[\| 1.0; 2.0 \|\] \[\| 3.0; 4.0 \|\];; - : float array = \[\|4.; 6.\|\] ``` Record fields can also be modified by assignment, provided they are declared mutable in the definition of the record type: ```ocaml # type mutable_point = { mutable x: float; mutable y: float };; type mutable_point = { mutable x : float; mutable y : float; } # let translate p dx dy = p.x \<- p.x +. dx; p.y \<- p.y +. dy;; val translate : mutable_point -> float -> float -> unit = \<fun\> # let mypoint = { x = 0.0; y = 0.0 };; val mypoint : mutable_point = {x = 0.; y = 0.} # translate mypoint 1.0 2.0;; - : unit = () # mypoint;; - : mutable_point = {x = 1.; y = 2.} ```
## 5 Imperative features OCaml has no built-in notion of variable – identifiers whose current value can be changed by assignment. (The let binding is not an assignment, it introduces a new identifier with a new scope.) However, the standard library provides references, which are mutable indirection cells, with operators ! to fetch the current contents of the reference and := to assign the contents. Variables can then be emulated by let-binding a reference. For instance, here is an in-place insertion sort over arrays: ```ocaml # let insertion_sort a = for i = 1 to Array.length a - 1 do let val_i = a.(i) in let j = ref i in while !j \> 0 && val_i \< a.(!j - 1) do a.(!j) \<- a.(!j - 1); j := !j - 1 done; a.(!j) \<- val_i done;; val insertion_sort : 'a array -> unit = \<fun\> ``` References are also useful to write functions that maintain a current state between two calls to the function. For instance, the following pseudo-random number generator keeps the last returned number in a reference: ```ocaml # let current_rand = ref 0;; val current_rand : int ref = {contents = 0} # let random () = current_rand := !current_rand \* 25713 + 1345; !current_rand;; val random : unit -> int = \<fun\> ``` Again, there is nothing magical with references: they are implemented as a single-field mutable record, as follows. ```ocaml # type 'a ref = { mutable contents: 'a };; type 'a ref = { mutable contents : 'a; } # let ( ! ) r = r.contents;; val ( ! ) : 'a ref -> 'a = \<fun\> # let ( := ) r newval = r.contents \<- newval;; val ( := ) : 'a ref -> 'a -> unit = \<fun\> ```
## 5 Imperative features In some special cases, you may need to store a polymorphic function in a data structure, keeping its polymorphism. Doing this requires user-provided type annotations, since polymorphism is only introduced automatically for global definitions. However, you can explicitly give polymorphic types to record fields. ```ocaml # type idref = { mutable id: 'a. 'a -> 'a };; type idref = { mutable id : 'a. 'a -> 'a; } # let r = {id = fun x -> x};; val r : idref = {id = \<fun\>} # let g s = (s.id 1, s.id true);; val g : idref -> int \* bool = \<fun\> # r.id \<- (fun x -> print_string "called id\\n"; x);; - : unit = () # g r;; ``` called id called id - : int \* bool = (1, true)
## 6 Exceptions OCaml provides exceptions for signalling and handling exceptional conditions. Exceptions can also be used as a general-purpose non-local control structure, although this should not be overused since it can make the code harder to understand. Exceptions are declared with the exception construct, and signalled with the raise operator. For instance, the function below for taking the head of a list uses an exception to signal the case where an empty list is given. ```ocaml # exception Empty_list;; ``` exception Empty_list ```ocaml # let head l = match l with \[\] -> raise Empty_list \| hd :: tl -> hd;; val head : 'a list -> 'a = \<fun\> # head \[1; 2\];; - : int = 1 # head \[\];; Exception: Empty_list. ``` Exceptions are used throughout the standard library to signal cases where the library functions cannot complete normally. For instance, the List.assoc function, which returns the data associated with a given key in a list of (key, data) pairs, raises the predefined exception Not_found when the key does not appear in the list: ```ocaml # List.assoc 1 \[(0, "zero"); (1, "one")\];; - : string = "one" # List.assoc 2 \[(0, "zero"); (1, "one")\];; Exception: Not_found. ``` Exceptions can be trapped with the try…with construct: ```ocaml # let name_of_binary_digit digit = try List.assoc digit \[0, "zero"; 1, "one"\] with Not_found -> "not a binary digit";; val name_of_binary_digit : int -> string = \<fun\> # name_of_binary_digit 0;; - : string = "zero" # name_of_binary_digit (-1);; - : string = "not a binary digit" ```
## 6 Exceptions The with part does pattern matching on the exception value with the same syntax and behavior as match. Thus, several exceptions can be caught by one try…with construct: ```ocaml # let rec first_named_value values names = try List.assoc (head values) names with \| Empty_list -> "no named value" \| Not_found -> first_named_value (List.tl values) names;; val first_named_value : 'a list -> ('a \* string) list -> string = \<fun\> # first_named_value \[0; 10\] \[1, "one"; 10, "ten"\];; - : string = "ten" ``` Also, finalization can be performed by trapping all exceptions, performing the finalization, then re-raising the exception: ```ocaml # let temporarily_set_reference ref newval funct = let oldval = !ref in try ref := newval; let res = funct () in ref := oldval; res with x -> ref := oldval; raise x;; val temporarily_set_reference : 'a ref -> 'a -> (unit -> 'b) -> 'b = \<fun\> ``` An alternative to try…with is to catch the exception while pattern matching: ```ocaml # let assoc_may_map f x l = match List.assoc x l with \| exception Not_found -> None \| y -> f y;; val assoc_may_map : ('a -> 'b option) -> 'c -> ('c \* 'a) list -> 'b option = \<fun\> ``` Note that this construction is only useful if the exception is raised between match…with. Exception patterns can be combined with ordinary patterns at the toplevel, ```ocaml # let flat_assoc_opt x l = match List.assoc x l with \| None \| exception Not_found -> None \| Some \_ as v -> v;; val flat_assoc_opt : 'a -> ('a \* 'b option) list -> 'b option = \<fun\> ```
## 6 Exceptions but they cannot be nested inside other patterns. For instance, the pattern Some (exception A) is invalid. When exceptions are used as a control structure, it can be useful to make them as local as possible by using a locally defined exception. For instance, with ```ocaml # let fixpoint f x = let exception Done in let x = ref x in try while true do let y = f !x in if !x = y then raise Done else x := y done with Done -> !x;; val fixpoint : ('a -> 'a) -> 'a -> 'a = \<fun\> ``` the function f cannot raise a Done exception, which removes an entire class of misbehaving functions.
## 7 Lazy expressions OCaml allows us to defer some computation until later when we need the result of that computation. We use lazy (expr) to delay the evaluation of some expression expr. For example, we can defer the computation of 1+1 until we need the result of that expression, 2. Let us see how we initialize a lazy expression. ```ocaml # let lazy_two = lazy (print_endline "lazy_two evaluation"; 1 + 1);; val lazy_two : int lazy_t = \<lazy\> ``` We added print_endline "lazy_two evaluation" to see when the lazy expression is being evaluated. The value of lazy_two is displayed as \<lazy>, which means the expression has not been evaluated yet, and its final value is unknown. Note that lazy_two has type int lazy_t. However, the type 'a lazy_t is an internal type name, so the type 'a Lazy.t should be preferred when possible. When we finally need the result of a lazy expression, we can call Lazy.force on that expression to force its evaluation. The function force comes from standard-library module [Lazy](../5.2/api/Lazy.html). ```ocaml # Lazy.force lazy_two;; ``` lazy_two evaluation - : int = 2 Notice that our function call above prints “lazy_two evaluation” and then returns the plain value of the computation. Now if we look at the value of lazy_two, we see that it is not displayed as \<lazy> anymore but as lazy 2. ```ocaml # lazy_two;; - : int lazy_t = lazy 2 ```
## 7 Lazy expressions This is because Lazy.force memoizes the result of the forced expression. In other words, every subsequent call of Lazy.force on that expression returns the result of the first computation without recomputing the lazy expression. Let us force lazy_two once again. ```ocaml # Lazy.force lazy_two;; - : int = 2 ``` The expression is not evaluated this time; notice that “lazy_two evaluation” is not printed. The result of the initial computation is simply returned. Lazy patterns provide another way to force a lazy expression. ```ocaml # let lazy_l = lazy (\[1; 2\] @ \[3; 4\]);; val lazy_l : int list lazy_t = \<lazy\> # let lazy l = lazy_l;; val l : int list = \[1; 2; 3; 4\] ``` We can also use lazy patterns in pattern matching. ```ocaml # let maybe_eval lazy_guard lazy_expr = match lazy_guard, lazy_expr with \| lazy false, \_ -> "matches if (Lazy.force lazy_guard = false); lazy_expr not forced" \| lazy true, lazy \_ -> "matches if (Lazy.force lazy_guard = true); lazy_expr forced";; val maybe_eval : bool lazy_t -> 'a lazy_t -> string = \<fun\> ``` The lazy expression lazy_expr is forced only if the lazy_guard value yields true once computed. Indeed, a simple wildcard pattern (not lazy) never forces the lazy expression’s evaluation. However, a pattern with keyword lazy, even if it is wildcard, always forces the evaluation of the deferred computation.
## 8 Symbolic processing of expressions We finish this introduction with a more complete example representative of the use of OCaml for symbolic processing: formal manipulations of arithmetic expressions containing variables. The following variant type describes the expressions we shall manipulate: ```ocaml # type expression = Const of float \| Var of string \| Sum of expression \* expression (\* e1 + e2 \*) \| Diff of expression \* expression (\* e1 - e2 \*) \| Prod of expression \* expression (\* e1 \* e2 \*) \| Quot of expression \* expression (\* e1 / e2 \*) ;; type expression = Const of float \| Var of string \| Sum of expression \* expression \| Diff of expression \* expression \| Prod of expression \* expression \| Quot of expression \* expression ``` We first define a function to evaluate an expression given an environment that maps variable names to their values. For simplicity, the environment is represented as an association list. ```ocaml # exception Unbound_variable of string;; ``` exception Unbound_variable of string ```ocaml # let rec eval env exp = match exp with Const c -> c \| Var v -> (try List.assoc v env with Not_found -> raise (Unbound_variable v)) \| Sum(f, g) -> eval env f +. eval env g \| Diff(f, g) -> eval env f -. eval env g \| Prod(f, g) -> eval env f \*. eval env g \| Quot(f, g) -> eval env f /. eval env g;; val eval : (string \* float) list -> expression -> float = \<fun\> # eval \[("x", 1.0); ("y", 3.14)\] (Prod(Sum(Var "x", Const 2.0), Var "y"));; - : float = 9.42 ```
## 8 Symbolic processing of expressions Now for a real symbolic processing, we define the derivative of an expression with respect to a variable dv: ```ocaml # let rec deriv exp dv = match exp with Const c -> Const 0.0 \| Var v -> if v = dv then Const 1.0 else Const 0.0 \| Sum(f, g) -> Sum(deriv f dv, deriv g dv) \| Diff(f, g) -> Diff(deriv f dv, deriv g dv) \| Prod(f, g) -> Sum(Prod(f, deriv g dv), Prod(deriv f dv, g)) \| Quot(f, g) -> Quot(Diff(Prod(deriv f dv, g), Prod(f, deriv g dv)), Prod(g, g)) ;; val deriv : expression -> string -> expression = \<fun\> # deriv (Quot(Const 1.0, Var "x")) "x";; - : expression = Quot (Diff (Prod (Const 0., Var "x"), Prod (Const 1., Const 1.)), Prod (Var "x", Var "x")) ```
## 9 Pretty-printing As shown in the examples above, the internal representation (also called *abstract syntax*) of expressions quickly becomes hard to read and write as the expressions get larger. We need a printer and a parser to go back and forth between the abstract syntax and the *concrete syntax*, which in the case of expressions is the familiar algebraic notation (e.g. 2\*x+1). For the printing function, we take into account the usual precedence rules (i.e. \* binds tighter than +) to avoid printing unnecessary parentheses. To this end, we maintain the current operator precedence and print parentheses around an operator only if its precedence is less than the current precedence.
## 9 Pretty-printing ```ocaml # let print_expr exp = (\* Local function definitions \*) let open_paren prec op_prec = if prec \> op_prec then print_string "(" in let close_paren prec op_prec = if prec \> op_prec then print_string ")" in let rec print prec exp = (\* prec is the current precedence \*) match exp with Const c -> print_float c \| Var v -> print_string v \| Sum(f, g) -> open_paren prec 0; print 0 f; print_string " + "; print 0 g; close_paren prec 0 \| Diff(f, g) -> open_paren prec 0; print 0 f; print_string " - "; print 1 g; close_paren prec 0 \| Prod(f, g) -> open_paren prec 2; print 2 f; print_string " \* "; print 2 g; close_paren prec 2 \| Quot(f, g) -> open_paren prec 2; print 2 f; print_string " / "; print 3 g; close_paren prec 2 in print 0 exp;; val print_expr : expression -> unit = \<fun\> # let e = Sum(Prod(Const 2.0, Var "x"), Const 1.0);; val e : expression = Sum (Prod (Const 2., Var "x"), Const 1.) # print_expr e; print_newline ();; ``` 2\. \* x + 1. - : unit = () ```ocaml # print_expr (deriv e "x"); print_newline ();; ``` 2\. \* 1. + 0. \* x + 0. - : unit = ()
## 10 Printf formats There is a printf function in the [Printf](../5.2/api/Printf.html) module (see chapter ‍[2](moduleexamples.html#c%3Amoduleexamples)) that allows you to make formatted output more concisely. It follows the behavior of the printf function from the C standard library. The printf function takes a format string that describes the desired output as a text interspersed with specifiers (for instance %d, %f). Next, the specifiers are substituted by the following arguments in their order of apparition in the format string: ```ocaml # Printf.printf "%i + %i is an integer value, %F \* %F is a float, %S\\n" 3 2 4.5 1. "this is a string";; ``` 3 + 2 is an integer value, 4.5 \* 1. is a float, "this is a string" - : unit = () The OCaml type system checks that the type of the arguments and the specifiers are compatible. If you pass it an argument of a type that does not correspond to the format specifier, the compiler will display an error message: ```ocaml # Printf.printf "Float value: %F" 42;; Error: This expression has type int but an expression was expected of type float Hint: Did you mean 42.? ``` The fprintf function is like printf except that it takes an output channel as the first argument. The %a specifier can be useful to define custom printers (for custom types). For instance, we can create a printing template that converts an integer argument to signed decimal: ```ocaml # let pp_int ppf n = Printf.fprintf ppf "%d" n;; val pp_int : out_channel -> int -> unit = \<fun\> # Printf.printf "Outputting an integer using a custom printer: %a " pp_int 42;; ```
## 10 Printf formats Outputting an integer using a custom printer: 42 - : unit = () The advantage of those printers based on the %a specifier is that they can be composed together to create more complex printers step by step. We can define a combinator that can turn a printer for 'a type into a printer for 'a optional: ```ocaml # let pp_option printer ppf = function \| None -> Printf.fprintf ppf "None" \| Some v -> Printf.fprintf ppf "Some(%a)" printer v;; val pp_option : (out_channel -> 'a -> unit) -> out_channel -> 'a option -> unit = \<fun\> # Printf.fprintf stdout "The current setting is %a. \\nThere is only %a\\n" (pp_option pp_int) (Some 3) (pp_option pp_int) None ;; ``` The current setting is Some(3). There is only None - : unit = () If the value of its argument its None, the printer returned by pp_option printer prints None otherwise it uses the provided printer to print Some . Here is how to rewrite the pretty-printer using fprintf:
## 10 Printf formats ```ocaml # let pp_expr ppf expr = let open_paren prec op_prec output = if prec \> op_prec then Printf.fprintf output "%s" "(" in let close_paren prec op_prec output = if prec \> op_prec then Printf.fprintf output "%s" ")" in let rec print prec ppf expr = match expr with \| Const c -> Printf.fprintf ppf "%F" c \| Var v -> Printf.fprintf ppf "%s" v \| Sum(f, g) -> open_paren prec 0 ppf; Printf.fprintf ppf "%a + %a" (print 0) f (print 0) g; close_paren prec 0 ppf \| Diff(f, g) -> open_paren prec 0 ppf; Printf.fprintf ppf "%a - %a" (print 0) f (print 1) g; close_paren prec 0 ppf \| Prod(f, g) -> open_paren prec 2 ppf; Printf.fprintf ppf "%a \* %a" (print 2) f (print 2) g; close_paren prec 2 ppf \| Quot(f, g) -> open_paren prec 2 ppf; Printf.fprintf ppf "%a / %a" (print 2) f (print 3) g; close_paren prec 2 ppf in print 0 ppf expr;; val pp_expr : out_channel -> expression -> unit = \<fun\> # pp_expr stdout e; print_newline ();; ``` 2\. \* x + 1. - : unit = () ```ocaml # pp_expr stdout (deriv e "x"); print_newline ();; ``` 2\. \* 1. + 0. \* x + 0. - : unit = () Due to the way that format strings are built, storing a format string requires an explicit type annotation: ```ocaml # let str : \_ format = "%i is an integer value, %F is a float, %S\\n";; # Printf.printf str 3 4.5 "string value";; ``` 3 is an integer value, 4.5 is a float, "string value" - : unit = ()
## 11 Standalone OCaml programs All examples given so far were executed under the interactive system. OCaml code can also be compiled separately and executed non-interactively using the batch compilers ocamlc and ocamlopt. The source code must be put in a file with extension .ml. It consists of a sequence of phrases, which will be evaluated at runtime in their order of appearance in the source file. Unlike in interactive mode, types and values are not printed automatically; the program must call printing functions explicitly to produce some output. The ;; used in the interactive examples is not required in source files created for use with OCaml compilers, but can be helpful to mark the end of a top-level expression unambiguously even when there are syntax errors. Here is a sample standalone program to print the greatest common divisor (gcd) of two numbers: (* File gcd.ml *) let rec gcd a b = if b = 0 then a else gcd b (a mod b);; let main () = let a = int_of_string Sys.argv.(1) in let b = int_of_string Sys.argv.(2) in Printf.printf "%d\n" (gcd a b); exit 0;; main ();; Sys.argv is an array of strings containing the command-line parameters. Sys.argv.(1) is thus the first command-line parameter. The program above is compiled and executed with the following shell commands: $ ocamlc -o gcd gcd.ml $ ./gcd 6 9 3 $ ./gcd 7 11 1
## 11 Standalone OCaml programs More complex standalone OCaml programs are typically composed of multiple source files, and can link with precompiled libraries. Chapters ‍[13](comp.html#c%3Acamlc) and ‍[16](native.html#c%3Anativecomp) explain how to use the batch compilers ocamlc and ocamlopt. Recompilation of multi-file OCaml projects can be automated using third-party build systems, such as [dune](https://github.com/ocaml/dune). ------------------------------------------------------------------------ [« Foreword](foreword.html)[The module system »](moduleexamples.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The module system Source: https://ocaml.org/manual/5.2/moduleexamples.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [Polymorphism and its limitations](polymorphism.html) - [Generalized algebraic datatypes](gadts-tutorial.html) - [Advanced examples with classes and modules](advexamples.html) - [Parallel programming](parallelism.html) - [Memory model: The hard bits](memorymodel.html)
# Chapter 2 The module system This chapter introduces the module system of OCaml.
## 1 Structures A primary motivation for modules is to package together related definitions (such as the definitions of a data type and associated operations over that type) and enforce a consistent naming scheme for these definitions. This avoids running out of names or accidentally confusing names. Such a package is called a *structure* and is introduced by the struct…end construct, which contains an arbitrary sequence of definitions. The structure is usually given a name with the module binding. For instance, here is a structure packaging together a type of FIFO queues and their operations: ```ocaml # module Fifo = struct type 'a queue = { front: 'a list; rear: 'a list } let make front rear = match front with \| \[\] -> { front = List.rev rear; rear = \[\] } \| \_ -> { front; rear } let empty = { front = \[\]; rear = \[\] } let is_empty = function { front = \[\]; \_ } -> true \| \_ -> false let add x q = make q.front (x :: q.rear) exception Empty let top = function \| { front = \[\]; \_ } -> raise Empty \| { front = x :: \_; \_ } -> x let pop = function \| { front = \[\]; \_ } -> raise Empty \| { front = \_ :: f; rear = r } -> make f r end;; ``` module Fifo : sig type 'a queue = { front : 'a list; rear : 'a list; } val make : 'a list -> 'a list -> 'a queue val empty : 'a queue val is_empty : 'a queue -> bool val add : 'a -> 'a queue -> 'a queue exception Empty val top : 'a queue -> 'a val pop : 'a queue -> 'a queue end
## 1 Structures Outside the structure, its components can be referred to using the “dot notation”, that is, identifiers qualified by a structure name. For instance, Fifo.add is the function add defined inside the structure Fifo and Fifo.queue is the type queue defined in Fifo. ```ocaml # Fifo.add "hello" Fifo.empty;; - : string Fifo.queue = {Fifo.front = \["hello"\]; rear = \[\]} ``` Another possibility is to open the module, which brings all identifiers defined inside the module into the scope of the current structure. ```ocaml # open Fifo;; # add "hello" empty;; - : string Fifo.queue = {front = \["hello"\]; rear = \[\]} ``` Opening a module enables lighter access to its components, at the cost of making it harder to identify in which module an identifier has been defined. In particular, opened modules can shadow identifiers present in the current scope, potentially leading to confusing errors: ```ocaml # let empty = \[\] open Fifo;; val empty : 'a list = \[\] # let x = 1 :: empty ;; Error: This expression has type 'a Fifo.queue but an expression was expected of type int list ``` A partial solution to this conundrum is to open modules locally, making the components of the module available only in the concerned expression. This can also make the code both easier to read (since the open statement is closer to where it is used) and easier to refactor (since the code fragment is more self-contained). Two constructions are available for this purpose: ```ocaml # let open Fifo in add "hello" empty;; - : string Fifo.queue = {front = \["hello"\]; rear = \[\]} ``` and
## 1 Structures ```ocaml # Fifo.(add "hello" empty);; - : string Fifo.queue = {front = \["hello"\]; rear = \[\]} ``` In the second form, when the body of a local open is itself delimited by parentheses, braces or bracket, the parentheses of the local open can be omitted. For instance, ```ocaml # Fifo.\[empty\] = Fifo.(\[empty\]);; - : bool = true # Fifo.\[\|empty\|\] = Fifo.(\[\|empty\|\]);; - : bool = true # Fifo.{ contents = empty } = Fifo.({ contents = empty });; - : bool = true ``` This second form also works for patterns: ```ocaml # let at_most_one_element x = match x with \| Fifo.{ front = (\[\] \| \[\_\]); rear = \[\] } -> true \| \_ -> false ;; val at_most_one_element : 'a Fifo.queue -> bool = \<fun\> ``` It is also possible to copy the components of a module inside another module by using an include statement. This can be particularly useful to extend existing modules. As an illustration, we could add functions that return an optional value rather than an exception when the queue is empty. ```ocaml # module FifoOpt = struct include Fifo let top_opt q = if is_empty q then None else Some(top q) let pop_opt q = if is_empty q then None else Some(pop q) end;; ``` module FifoOpt : sig type 'a queue = 'a Fifo.queue = { front : 'a list; rear : 'a list; } val make : 'a list -> 'a list -> 'a queue val empty : 'a queue val is_empty : 'a queue -> bool val add : 'a -> 'a queue -> 'a queue exception Empty val top : 'a queue -> 'a val pop : 'a queue -> 'a queue val top_opt : 'a queue -> 'a option val pop_opt : 'a queue -> 'a queue option end
## 2 Signatures Signatures are interfaces for structures. A signature specifies which components of a structure are accessible from the outside, and with which type. It can be used to hide some components of a structure (e.g. local function definitions) or export some components with a restricted type. For instance, the signature below specifies the queue operations empty, add, top and pop, but not the auxiliary function make. Similarly, it makes the queue type abstract (by not providing its actual representation as a concrete type). This ensures that users of the Fifo module cannot violate data structure invariants that operations rely on, such as “if the front list is empty, the rear list must also be empty”. ```ocaml # module type FIFO = sig type 'a queue (\* now an abstract type \*) val empty : 'a queue val add : 'a -> 'a queue -> 'a queue val top : 'a queue -> 'a val pop : 'a queue -> 'a queue exception Empty end;; ``` module type FIFO = sig type 'a queue val empty : 'a queue val add : 'a -> 'a queue -> 'a queue val top : 'a queue -> 'a val pop : 'a queue -> 'a queue exception Empty end Restricting the Fifo structure to this signature results in another view of the Fifo structure where the make function is not accessible and the actual representation of queues is hidden: ```ocaml # module AbstractQueue = (Fifo : FIFO);; ``` module AbstractQueue : FIFO ```ocaml # AbstractQueue.make \[1\] \[2;3\] ;; Error: Unbound value AbstractQueue.make # AbstractQueue.add "hello" AbstractQueue.empty;; - : string AbstractQueue.queue = \<abstr> ```
## 2 Signatures The restriction can also be performed during the definition of the structure, as in module Fifo = (struct ... end : FIFO);; An alternate syntax is provided for the above: module Fifo : FIFO = struct ... end;; Like for modules, it is possible to include a signature to copy its components inside the current signature. For instance, we can extend the FIFO signature with the top_opt and pop_opt functions: ```ocaml # module type FIFO_WITH_OPT = sig include FIFO val top_opt: 'a queue -> 'a option val pop_opt: 'a queue -> 'a queue option end;; ``` module type FIFO_WITH_OPT = sig type 'a queue val empty : 'a queue val add : 'a -> 'a queue -> 'a queue val top : 'a queue -> 'a val pop : 'a queue -> 'a queue exception Empty val top_opt : 'a queue -> 'a option val pop_opt : 'a queue -> 'a queue option end
## 3 Functors Functors are “functions” from modules to modules. Functors let you create parameterized modules and then provide other modules as parameter(s) to get a specific implementation. For instance, a Set module implementing sets as sorted lists could be parameterized to work with any module that provides an element type and a comparison function compare (such as OrderedString): ```ocaml # type comparison = Less \| Equal \| Greater;; type comparison = Less \| Equal \| Greater # module type ORDERED_TYPE = sig type t val compare: t -> t -> comparison end;; ``` module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end ```ocaml # module Set = functor (Elt: ORDERED_TYPE) -> struct type element = Elt.t type set = element list let empty = \[\] let rec add x s = match s with \[\] -> \[x\] \| hd::tl -> match Elt.compare x hd with Equal -> s (\* x is already in s \*) \| Less -> x :: s (\* x is smaller than all elements of s \*) \| Greater -> hd :: add x tl let rec member x s = match s with \[\] -> false \| hd::tl -> match Elt.compare x hd with Equal -> true (\* x belongs to s \*) \| Less -> false (\* x is smaller than all elements of s \*) \| Greater -> member x tl end;; ``` module Set : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set = element list val empty : 'a list val add : Elt.t -> Elt.t list -> Elt.t list val member : Elt.t -> Elt.t list -> bool end By applying the Set functor to a structure implementing an ordered type, we obtain set operations for this type:
## 3 Functors ```ocaml # module OrderedString = struct type t = string let compare x y = if x = y then Equal else if x \< y then Less else Greater end;; ``` module OrderedString : sig type t = string val compare : 'a -> 'a -> comparison end ```ocaml # module StringSet = Set(OrderedString);; ``` module StringSet : sig type element = OrderedString.t type set = element list val empty : 'a list val add : OrderedString.t -> OrderedString.t list -> OrderedString.t list val member : OrderedString.t -> OrderedString.t list -> bool end ```ocaml # StringSet.member "bar" (StringSet.add "foo" StringSet.empty);; - : bool = false ```
## 4 Functors and type abstraction As in the Fifo example, it would be good style to hide the actual implementation of the type set, so that users of the structure will not rely on sets being lists, and we can switch later to another, more efficient representation of sets without breaking their code. This can be achieved by restricting Set by a suitable functor signature: ```ocaml # module type SETFUNCTOR = functor (Elt: ORDERED_TYPE) -> sig type element = Elt.t (\* concrete \*) type set (\* abstract \*) val empty : set val add : element -> set -> set val member : element -> set -> bool end;; ``` module type SETFUNCTOR = functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set val empty : set val add : element -> set -> set val member : element -> set -> bool end ```ocaml # module AbstractSet = (Set : SETFUNCTOR);; ``` module AbstractSet : SETFUNCTOR ```ocaml # module AbstractStringSet = AbstractSet(OrderedString);; ``` module AbstractStringSet : sig type element = OrderedString.t type set = AbstractSet(OrderedString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end ```ocaml # AbstractStringSet.add "gee" AbstractStringSet.empty;; - : AbstractStringSet.set = \<abstr> ``` In an attempt to write the type constraint above more elegantly, one may wish to name the signature of the structure returned by the functor, then use that signature in the constraint: ```ocaml # module type SET = sig type element type set val empty : set val add : element -> set -> set val member : element -> set -> bool end;; ```
## 4 Functors and type abstraction module type SET = sig type element type set val empty : set val add : element -> set -> set val member : element -> set -> bool end ```ocaml # module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);; ``` module WrongSet : functor (Elt : ORDERED_TYPE) -> SET ```ocaml # module WrongStringSet = WrongSet(OrderedString);; ``` module WrongStringSet : sig type element = WrongSet(OrderedString).element type set = WrongSet(OrderedString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end ```ocaml # WrongStringSet.add "gee" WrongStringSet.empty ;; Error: This expression has type string but an expression was expected of type WrongStringSet.element = WrongSet(OrderedString).element ``` The problem here is that SET specifies the type element abstractly, so that the type equality between element in the result of the functor and t in its argument is forgotten. Consequently, WrongStringSet.element is not the same type as string, and the operations of WrongStringSet cannot be applied to strings. As demonstrated above, it is important that the type element in the signature SET be declared equal to Elt.t; unfortunately, this is impossible above since SET is defined in a context where Elt does not exist. To overcome this difficulty, OCaml provides a with type construct over signatures that allows enriching a signature with extra type equalities: ```ocaml # module AbstractSet2 = (Set : functor(Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));; ```
## 4 Functors and type abstraction module AbstractSet2 : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set val empty : set val add : element -> set -> set val member : element -> set -> bool end As in the case of simple structures, an alternate syntax is provided for defining functors and restricting their result: module AbstractSet2(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) = struct ... end;; Abstracting a type component in a functor result is a powerful technique that provides a high degree of type safety, as we now illustrate. Consider an ordering over character strings that is different from the standard ordering implemented in the OrderedString structure. For instance, we compare strings without distinguishing upper and lower case. ```ocaml # module NoCaseString = struct type t = string let compare s1 s2 = OrderedString.compare (String.lowercase_ascii s1) (String.lowercase_ascii s2) end;; ``` module NoCaseString : sig type t = string val compare : string -> string -> comparison end ```ocaml # module NoCaseStringSet = AbstractSet(NoCaseString);; ``` module NoCaseStringSet : sig type element = NoCaseString.t type set = AbstractSet(NoCaseString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end ```ocaml # NoCaseStringSet.add "FOO" AbstractStringSet.empty ;; Error: This expression has type AbstractStringSet.set = AbstractSet(OrderedString).set but an expression was expected of type NoCaseStringSet.set = AbstractSet(NoCaseString).set ```
## 4 Functors and type abstraction Note that the two types AbstractStringSet.set and NoCaseStringSet.set are not compatible, and values of these two types do not match. This is the correct behavior: even though both set types contain elements of the same type (strings), they are built upon different orderings of that type, and different invariants need to be maintained by the operations (being strictly increasing for the standard ordering and for the case-insensitive ordering). Applying operations from AbstractStringSet to values of type NoCaseStringSet.set could give incorrect results, or build lists that violate the invariants of NoCaseStringSet.
## 5 Modules and separate compilation All examples of modules so far have been given in the context of the interactive system. However, modules are most useful for large, batch-compiled programs. For these programs, it is a practical necessity to split the source into several files, called compilation units, that can be compiled separately, thus minimizing recompilation after changes. In OCaml, compilation units are special cases of structures and signatures, and the relationship between the units can be explained easily in terms of the module system. A compilation unit A comprises two files: - the implementation file A.ml, which contains a sequence of definitions, analogous to the inside of a struct…end construct; - the interface file A.mli, which contains a sequence of specifications, analogous to the inside of a sig…end construct. These two files together define a structure named A as if the following definition was entered at top-level: module A: sig (* contents of file A.mli *) end = struct (* contents of file A.ml *) end;; The files that define the compilation units can be compiled separately using the ocamlc -c command (the -c option means “compile only, do not try to link”); this produces compiled interface files (with extension .cmi) and compiled object code files (with extension .cmo). When all units have been compiled, their .cmo files are linked together using the ocamlc command. For instance, the following commands compile and link a program composed of two compilation units Aux and Main:
## 5 Modules and separate compilation $ ocamlc -c Aux.mli # produces aux.cmi $ ocamlc -c Aux.ml # produces aux.cmo $ ocamlc -c Main.mli # produces main.cmi $ ocamlc -c Main.ml # produces main.cmo $ ocamlc -o theprogram Aux.cmo Main.cmo The program behaves exactly as if the following phrases were entered at top-level: module Aux: sig (* contents of Aux.mli *) end = struct (* contents of Aux.ml *) end;; module Main: sig (* contents of Main.mli *) end = struct (* contents of Main.ml *) end;; In particular, Main can refer to Aux: the definitions and declarations contained in Main.ml and Main.mli can refer to definition in Aux.ml, using the Aux.ident notation, provided these definitions are exported in Aux.mli. The order in which the .cmo files are given to ocamlc during the linking phase determines the order in which the module definitions occur. Hence, in the example above, Aux appears first and Main can refer to it, but Aux cannot refer to Main. Note that only top-level structures can be mapped to separately-compiled files, but neither functors nor module types. However, all module-class objects can appear as components of a structure, so the solution is to put the functor or module type inside a structure, which can then be mapped to a file. ------------------------------------------------------------------------ [« The core language](coreexamples.html)[Objects in OCaml »](objectexamples.html)
## 5 Modules and separate compilation Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Objects in OCaml Source: https://ocaml.org/manual/5.2/objectexamples.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [Polymorphism and its limitations](polymorphism.html) - [Generalized algebraic datatypes](gadts-tutorial.html) - [Advanced examples with classes and modules](advexamples.html) - [Parallel programming](parallelism.html) - [Memory model: The hard bits](memorymodel.html)
# Chapter 3 Objects in OCaml This chapter gives an overview of the object-oriented features of OCaml. Note that the relationship between object, class and type in OCaml is different than in mainstream object-oriented languages such as Java and C++, so you shouldn’t assume that similar keywords mean the same thing. Object-oriented features are used much less frequently in OCaml than in those languages. OCaml has alternatives that are often more appropriate, such as modules and functors. Indeed, many OCaml programs do not use objects at all.
## 1 Classes and objects The class point below defines one instance variable x and two methods get_x and move. The initial value of the instance variable is 0. The variable x is declared mutable, so the method move can change its value. ```ocaml # class point = object val mutable x = 0 method get_x = x method move d = x \<- x + d end;; ``` class point : object val mutable x : int method get_x : int method move : int -> unit end We now create a new point p, instance of the point class. ```ocaml # let p = new point;; val p : point = \<obj> ``` Note that the type of p is point. This is an abbreviation automatically defined by the class definition above. It stands for the object type \<get_x : int; move : int -> unit>, listing the methods of class point along with their types. We now invoke some methods of p: ```ocaml # p#get_x;; - : int = 0 # p#move 3;; - : unit = () # p#get_x;; - : int = 3 ``` The evaluation of the body of a class only takes place at object creation time. Therefore, in the following example, the instance variable x is initialized to different values for two different objects. ```ocaml # let x0 = ref 0;; val x0 : int ref = {contents = 0} # class point = object val mutable x = incr x0; !x0 method get_x = x method move d = x \<- x + d end;; ``` class point : object val mutable x : int method get_x : int method move : int -> unit end ```ocaml # new point#get_x;; - : int = 1 # new point#get_x;; - : int = 2 ``` The class point can also be abstracted over the initial values of the x coordinate.
## 1 Classes and objects ```ocaml # class point = fun x_init -> object val mutable x = x_init method get_x = x method move d = x \<- x + d end;; ``` class point : int -> object val mutable x : int method get_x : int method move : int -> unit end Like in function definitions, the definition above can be abbreviated as: ```ocaml # class point x_init = object val mutable x = x_init method get_x = x method move d = x \<- x + d end;; ``` class point : int -> object val mutable x : int method get_x : int method move : int -> unit end An instance of the class point is now a function that expects an initial parameter to create a point object: ```ocaml # new point;; - : int -> point = \<fun\> # let p = new point 7;; val p : point = \<obj> ``` The parameter x_init is, of course, visible in the whole body of the definition, including methods. For instance, the method get_offset in the class below returns the position of the object relative to its initial position. ```ocaml # class point x_init = object val mutable x = x_init method get_x = x method get_offset = x - x_init method move d = x \<- x + d end;; ``` class point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end Expressions can be evaluated and bound before defining the object body of the class. This is useful to enforce invariants. For instance, points can be automatically adjusted to the nearest point on a grid, as follows:
## 1 Classes and objects ```ocaml # class adjusted_point x_init = let origin = (x_init / 10) \* 10 in object val mutable x = origin method get_x = x method get_offset = x - origin method move d = x \<- x + d end;; ``` class adjusted_point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end (One could also raise an exception if the x_init coordinate is not on the grid.) In fact, the same effect could be obtained here by calling the definition of class point with the value of the origin. ```ocaml # class adjusted_point x_init = point ((x_init / 10) \* 10);; ``` class adjusted_point : int -> point An alternate solution would have been to define the adjustment in a special allocation function: ```ocaml # let new_adjusted_point x_init = new point ((x_init / 10) \* 10);; val new_adjusted_point : int -> point = \<fun\> ``` However, the former pattern is generally more appropriate, since the code for adjustment is part of the definition of the class and will be inherited. This ability provides class constructors as can be found in other languages. Several constructors can be defined this way to build objects of the same class but with different initialization patterns; an alternative is to use initializers, as described below in section ‍[3.4](#s%3Ainitializers).
## 2 Immediate objects There is another, more direct way to create an object: create it without going through a class. The syntax is exactly the same as for class expressions, but the result is a single object rather than a class. All the constructs described in the rest of this section also apply to immediate objects. ```ocaml # let p = object val mutable x = 0 method get_x = x method move d = x \<- x + d end;; val p : \< get_x : int; move : int -> unit \> = \<obj> # p#get_x;; - : int = 0 # p#move 3;; - : unit = () # p#get_x;; - : int = 3 ``` Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment. ```ocaml # let minmax x y = if x \< y then object method min = x method max = y end else object method min = y method max = x end;; val minmax : 'a -> 'a -> \< max : 'a; min : 'a \> = \<fun\> ``` Immediate objects have two weaknesses compared to classes: their types are not abbreviated, and you cannot inherit from them. But these two weaknesses can be advantages in some situations, as we will see in sections ‍[3.3](#s%3Areference-to-self) and ‍[3.10](#s%3Aparameterized-classes).
## 3 Reference to self A method or an initializer can invoke methods on self (that is, the current object). For that, self must be explicitly bound, here to the variable s (s could be any identifier, even though we will often choose the name self.) ```ocaml # class printable_point x_init = object (s) val mutable x = x_init method get_x = x method move d = x \<- x + d method print = print_int s#get_x end;; ``` class printable_point : int -> object val mutable x : int method get_x : int method move : int -> unit method print : unit end ```ocaml # let p = new printable_point 7;; val p : printable_point = \<obj> # p#print;; ``` 7- : unit = () Dynamically, the variable s is bound at the invocation of a method. In particular, when the class printable_point is inherited, the variable s will be correctly bound to the object of the subclass. A common problem with self is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example. ```ocaml # let ints = ref \[\];; val ints : '\_weak1 list ref = {contents = \[\]} # class my_int = object (self) method n = 1 method register = ints := self :: !ints end ;; Error: This expression has type \< n : int; register : 'a; .. \> but an expression was expected of type 'weak1 Self type cannot escape its class ```
## 3 Reference to self You can ignore the first two lines of the error message. What matters is the last one: putting self into an external reference would make it impossible to extend it through inheritance. We will see in section ‍[3.12](#s%3Ausing-coercions) a workaround to this problem. Note however that, since immediate objects are not extensible, the problem does not occur with them. ```ocaml # let my_int = object (self) method n = 1 method register = ints := self :: !ints end;; val my_int : \< n : int; register : unit \> = \<obj> ```
## 4 Initializers Let-bindings within class definitions are evaluated before the object is constructed. It is also possible to evaluate an expression immediately after the object has been built. Such code is written as an anonymous hidden method called an initializer. Therefore, it can access self and the instance variables. ```ocaml # class printable_point x_init = let origin = (x_init / 10) \* 10 in object (self) val mutable x = origin method get_x = x method move d = x \<- x + d method print = print_int self#get_x initializer print_string "new point at "; self#print; print_newline () end;; ``` class printable_point : int -> object val mutable x : int method get_x : int method move : int -> unit method print : unit end ```ocaml # let p = new printable_point 17;; ``` new point at 10 val p : printable_point = \<obj> Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section ‍[8.1](advexamples.html#s%3Aextended-bank-accounts).
## 5 Virtual methods It is possible to declare a method without actually defining it, using the keyword virtual. This method will be provided later in subclasses. A class containing virtual methods must be flagged virtual, and cannot be instantiated (that is, no object of this class can be created). It still defines type abbreviations (treating virtual methods as other methods.) ```ocaml # class virtual abstract_point x_init = object (self) method virtual get_x : int method get_offset = self#get_x - x_init method virtual move : int -> unit end;; ``` class virtual abstract_point : int -> object method get_offset : int method virtual get_x : int method virtual move : int -> unit end ```ocaml # class point x_init = object inherit abstract_point x_init val mutable x = x_init method get_x = x method move d = x \<- x + d end;; ``` class point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end Instance variables can also be declared as virtual, with the same effect as with methods. ```ocaml # class virtual abstract_point2 = object val mutable virtual x : int method move d = x \<- x + d end;; ``` class virtual abstract_point2 : object val mutable virtual x : int method move : int -> unit end ```ocaml # class point2 x_init = object inherit abstract_point2 val mutable x = x_init method get_offset = x - x_init end;; ``` class point2 : int -> object val mutable x : int method get_offset : int method move : int -> unit end
## 6 Private methods Private methods are methods that do not appear in object interfaces. They can only be invoked from other methods of the same object. ```ocaml # class restricted_point x_init = object (self) val mutable x = x_init method get_x = x method private move d = x \<- x + d method bump = self#move 1 end;; ``` class restricted_point : int -> object val mutable x : int method bump : unit method get_x : int method private move : int -> unit end ```ocaml # let p = new restricted_point 0;; val p : restricted_point = \<obj> # p#move 10 ;; Error: This expression has type restricted_point It has no method move # p#bump;; - : unit = () ``` Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in OCaml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section ‍[3.17](#s%3Afriends). Private methods are inherited (they are by default visible in subclasses), unless they are hidden by signature matching, as described below. Private methods can be made public in a subclass. ```ocaml # class point_again x = object (self) inherit restricted_point x method virtual move : \_ end;; ``` class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
## 6 Private methods The annotation virtual here is only used to mention a method without providing its definition. Since we didn’t add the private annotation, this makes the method public, keeping the original definition. An alternative definition is ```ocaml # class point_again x = object (self : \< move : \_; ..> ) inherit restricted_point x end;; ``` class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end The constraint on self’s type is requiring a public move method, and this is sufficient to override private. One could think that a private method should remain private in a subclass. However, since the method is visible in a subclass, it is always possible to pick its code and define a method of the same name that runs that code, so yet another (heavier) solution would be: ```ocaml # class point_again x = object inherit restricted_point x as super method move = super#move end;; ``` class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end Of course, private methods can also be virtual. Then, the keywords must appear in this order: method private virtual.
## 7 Class interfaces Class interfaces are inferred from class definitions. They may also be defined directly and used to restrict the type of a class. Like class declarations, they also define a new type abbreviation. ```ocaml # class type restricted_point_type = object method get_x : int method bump : unit end;; ``` class type restricted_point_type = object method bump : unit method get_x : int end ```ocaml # fun (x : restricted_point_type) -> x;; - : restricted_point_type -> restricted_point_type = \<fun\> ``` In addition to program documentation, class interfaces can be used to constrain the type of a class. Both concrete instance variables and concrete private methods can be hidden by a class type constraint. Public methods and virtual members, however, cannot. ```ocaml # class restricted_point' x = (restricted_point x : restricted_point_type);; ``` class restricted_point' : int -> restricted_point_type Or, equivalently: ```ocaml # class restricted_point' = (restricted_point : int -> restricted_point_type);; ``` class restricted_point' : int -> restricted_point_type The interface of a class can also be specified in a module signature, and used to restrict the inferred signature of a module. ```ocaml # module type POINT = sig class restricted_point' : int -> object method get_x : int method bump : unit end end;; ``` module type POINT = sig class restricted_point' : int -> object method bump : unit method get_x : int end end ```ocaml # module Point : POINT = struct class restricted_point' = restricted_point end;; ``` module Point : POINT
## 8 Inheritance We illustrate inheritance by defining a class of colored points that inherits from the class of points. This class has all instance variables and all methods of class point, plus a new instance variable c and a new method color. ```ocaml # class colored_point x (c : string) = object inherit point x val c = c method color = c end;; ``` class colored_point : int -> string -> object val c : string val mutable x : int method color : string method get_offset : int method get_x : int method move : int -> unit end ```ocaml # let p' = new colored_point 5 "red";; val p' : colored_point = \<obj> # p'#get_x, p'#color;; - : int \* string = (5, "red") ``` A point and a colored point have incompatible types, since a point has no method color. However, the function get_x below is a generic function applying method get_x to any object p that has this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it applies to both points and colored points. ```ocaml # let get_succ_x p = p#get_x + 1;; val get_succ_x : \< get_x : int; .. \> -> int = \<fun\> # get_succ_x p + get_succ_x p';; - : int = 8 ``` Methods need not be declared previously, as shown by the example: ```ocaml # let set_x p = p#set_x;; val set_x : \< set_x : 'a; .. \> -> 'a = \<fun\> # let incr p = set_x p (get_succ_x p);; val incr : \< get_x : int; set_x : int -> 'a; .. \> -> 'a = \<fun\> ```
## 9 Multiple inheritance Multiple inheritance is allowed. Only the last definition of a method is kept: the redefinition in a subclass of a method that was visible in the parent class overrides the definition in the parent class. Previous definitions of a method can be reused by binding the related ancestor. Below, super is bound to the ancestor printable_point. The name super is a pseudo value identifier that can only be used to invoke a super-class method, as in super#print. ```ocaml # class printable_colored_point y c = object (self) val c = c method color = c inherit printable_point y as super method! print = print_string "("; super#print; print_string ", "; print_string (self#color); print_string ")" end;; ``` class printable_colored_point : int -> string -> object val c : string val mutable x : int method color : string method get_x : int method move : int -> unit method print : unit end ```ocaml # let p' = new printable_colored_point 17 "red";; ``` new point at (10, red) val p' : printable_colored_point = \<obj> ```ocaml # p'#print;; ``` (10, red)- : unit = () A private method that has been hidden in the parent class is no longer visible, and is thus not overridden. Since initializers are treated as private methods, all initializers along the class hierarchy are evaluated, in the order they are introduced.
## 9 Multiple inheritance Note that for clarity’s sake, the method print is explicitly marked as overriding another definition by annotating the method keyword with an exclamation mark !. If the method print were not overriding the print method of printable_point, the compiler would raise an error: ```ocaml # object method! m = () end;; Error: The method m has no previous definition ``` This explicit overriding annotation also works for val and inherit: ```ocaml # class another_printable_colored_point y c c' = object (self) inherit printable_point y inherit! printable_colored_point y c val! c = c' end;; ``` class another_printable_colored_point : int -> string -> string -> object val c : string val mutable x : int method color : string method get_x : int method move : int -> unit method print : unit end
## 10 Parameterized classes Reference cells can be implemented as objects. The naive definition fails to typecheck: ```ocaml # class oref x_init = object val mutable x = x_init method get = x method set y = x \<- y end;; Error: Some type variables are unbound in this type: class oref : 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end The method get has type 'a where 'a is unbound ``` The reason is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus either the class should be parametric, or the method type should be constrained to a monomorphic type. A monomorphic instance of the class could be defined by: ```ocaml # class oref (x_init:int) = object val mutable x = x_init method get = x method set y = x \<- y end;; ``` class oref : int -> object val mutable x : int method get : int method set : int -> unit end Note that since immediate objects do not define a class type, they have no such restriction. ```ocaml # let new_oref x_init = object val mutable x = x_init method get = x method set y = x \<- y end;; val new_oref : 'a -> \< get : 'a; set : 'a -> unit \> = \<fun\> ``` On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are listed between \[ and \]. The type parameters must also be bound somewhere in the class body by a type constraint. ```ocaml # class \['a\] oref x_init = object val mutable x = (x_init : 'a) method get = x method set y = x \<- y end;; ```
## 10 Parameterized classes class \['a\] oref : 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end ```ocaml # let r = new oref 1 in r#set 2; (r#get);; - : int = 2 ``` The type parameter in the declaration may actually be constrained in the body of the class definition. In the class type, the actual value of the type parameter is displayed in the constraint clause. ```ocaml # class \['a\] oref_succ (x_init:'a) = object val mutable x = x_init + 1 method get = x method set y = x \<- y end;; ``` class \['a\] oref_succ : 'a -> object constraint 'a = int val mutable x : int method get : int method set : int -> unit end Let us consider a more complex example: define a circle, whose center may be any kind of point. We put an additional type constraint in method move, since no free variables must remain unaccounted for by the class type parameters. ```ocaml # class \['a\] circle (c : 'a) = object val mutable center = c method center = center method set_center c = center \<- c method move = (center#move : int -> unit) end;; ``` class \['a\] circle : 'a -> object constraint 'a = \< move : int -> unit; .. \> val mutable center : 'a method center : 'a method move : int -> unit method set_center : 'a -> unit end
## 10 Parameterized classes An alternate definition of circle, using a constraint clause in the class definition, is shown below. The type #point used below in the constraint clause is an abbreviation produced by the definition of class point. This abbreviation unifies with the type of any object belonging to a subclass of class point. It actually expands to \< get_x : int; move : int -> unit; .. \>. This leads to the following alternate definition of circle, which has slightly stronger constraints on its argument, as we now expect center to have a method get_x. ```ocaml # class \['a\] circle (c : 'a) = object constraint 'a = #point val mutable center = c method center = center method set_center c = center \<- c method move = center#move end;; ``` class \['a\] circle : 'a -> object constraint 'a = #point val mutable center : 'a method center : 'a method move : int -> unit method set_center : 'a -> unit end The class colored_circle is a specialized version of class circle that requires the type of the center to unify with #colored_point, and adds a method color. Note that when specializing a parameterized class, the instance of type parameter must always be explicitly given. It is again written between \[ and \]. ```ocaml # class \['a\] colored_circle c = object constraint 'a = #colored_point inherit \['a\] circle c method color = center#color end;; ``` class \['a\] colored_circle : 'a -> object constraint 'a = #colored_point val mutable center : 'a method center : 'a method color : string method move : int -> unit method set_center : 'a -> unit end
## 11 Polymorphic methods While parameterized classes may be polymorphic in their contents, they are not enough to allow polymorphism of method use. A classical example is defining an iterator. ```ocaml # List.fold_left;; - : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc = \<fun\> # class \['a\] intlist (l : int list) = object method empty = (l = \[\]) method fold f (accu : 'a) = List.fold_left f accu l end;; ``` class \['a\] intlist : int list -> object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end At first look, we seem to have a polymorphic iterator, however this does not work in practice. ```ocaml # let l = new intlist \[1; 2; 3\];; val l : '\_weak2 intlist = \<obj> # l#fold (fun x y -> x+y) 0;; - : int = 6 # l;; - : int intlist = \<obj> # l#fold (fun s x -> s ^ Int.to_string x ^ " ") "" ;; Error: This expression has type int but an expression was expected of type string ``` Our iterator works, as shows its first use for summation. However, since objects themselves are not polymorphic (only their constructors are), using the fold method fixes its type for this individual object. Our next attempt to use it as a string iterator fails. The problem here is that quantification was wrongly located: it is not the class we want to be polymorphic, but the fold method. This can be achieved by giving an explicitly polymorphic type in the method definition. ```ocaml # class intlist (l : int list) = object method empty = (l = \[\]) method fold : 'a. ('a -> int -> 'a) -> 'a -> 'a = fun f accu -> List.fold_left f accu l end;; ```
## 11 Polymorphic methods class intlist : int list -> object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end ```ocaml # let l = new intlist \[1; 2; 3\];; val l : intlist = \<obj> # l#fold (fun x y -> x+y) 0;; - : int = 6 # l#fold (fun s x -> s ^ Int.to_string x ^ " ") "";; - : string = "1 2 3 " ``` As you can see in the class type shown by the compiler, while polymorphic method types must be fully explicit in class definitions (appearing immediately after the method name), quantified type variables can be left implicit in class descriptions. Why require types to be explicit? The problem is that (int -> int -> int) -> int -> int would also be a valid type for fold, and it happens to be incompatible with the polymorphic type we gave (automatic instantiation only works for toplevel types variables, not for inner quantifiers, where it becomes an undecidable problem.) So the compiler cannot choose between those two types, and must be helped. However, the type can be completely omitted in the class definition if it is already known, through inheritance or type constraints on self. Here is an example of method overriding. ```ocaml # class intlist_rev l = object inherit intlist l method! fold f accu = List.fold_left f accu (List.rev l) end;; ``` The following idiom separates description and definition. ```ocaml # class type \['a\] iterator = object method fold : ('b -> 'a -> 'b) -> 'b -> 'b end;; # class intlist' l = object (self : int #iterator) method empty = (l = \[\]) method fold f accu = List.fold_left f accu l end;; ```
## 11 Polymorphic methods Note here the (self : int #iterator) idiom, which ensures that this object implements the interface iterator. Polymorphic methods are called in exactly the same way as normal methods, but you should be aware of some limitations of type inference. Namely, a polymorphic method can only be called if its type is known at the call site. Otherwise, the method will be assumed to be monomorphic, and given an incompatible type. ```ocaml # let sum lst = lst#fold (fun x y -> x+y) 0;; val sum : \< fold : (int -> int -> int) -> int -> 'a; .. \> -> 'a = \<fun\> # sum l ;; Error: This expression has type intlist but an expression was expected of type \< fold : (int -> int -> int) -> int -> 'b; .. \> The method fold has type 'a. ('a -> int -> 'a) -> 'a -> 'a, but the expected method type was (int -> int -> int) -> int -> 'b ``` The workaround is easy: you should put a type constraint on the parameter. ```ocaml # let sum (lst : \_ #iterator) = lst#fold (fun x y -> x+y) 0;; val sum : int #iterator -> int = \<fun\> ``` Of course the constraint may also be an explicit method type. Only occurrences of quantified variables are required. ```ocaml # let sum lst = (lst : \< fold : 'a. ('a -> \_ -> 'a) -> 'a -> 'a; .. \>)#fold (+) 0;; val sum : \< fold : 'a. ('a -> int -> 'a) -> 'a -> 'a; .. \> -> int = \<fun\> ``` Another use of polymorphic methods is to allow some form of implicit subtyping in method arguments. We have already seen in section ‍[3.8](#s%3Ainheritance) how some functions may be polymorphic in the class of their argument. This can be extended to methods.
## 11 Polymorphic methods ```ocaml # class type point0 = object method get_x : int end;; ``` class type point0 = object method get_x : int end ```ocaml # class distance_point x = object inherit point x method distance : 'a. (#point0 as 'a) -> int = fun other -> abs (other#get_x - x) end;; ``` class distance_point : int -> object val mutable x : int method distance : #point0 -> int method get_offset : int method get_x : int method move : int -> unit end ```ocaml # let p = new distance_point 3 in (p#distance (new point 8), p#distance (new colored_point 1 "blue"));; - : int \* int = (5, 2) ``` Note here the special syntax (#point0 as 'a) we have to use to quantify the extensible part of #point0. As for the variable binder, it can be omitted in class specifications. If you want polymorphism inside object field it must be quantified independently. ```ocaml # class multi_poly = object method m1 : 'a. (\< n1 : 'b. 'b -> 'b; .. \> as 'a) -> \_ = fun o -> o#n1 true, o#n1 "hello" method m2 : 'a 'b. (\< n2 : 'b -> bool; .. \> as 'a) -> 'b -> \_ = fun o x -> o#n2 x end;; ``` class multi_poly : object method m1 : \< n1 : 'b. 'b -> 'b; .. \> -> bool \* string method m2 : \< n2 : 'b -> bool; .. \> -> 'b -> bool end In method m1, o must be an object with at least a method n1, itself polymorphic. In method m2, the argument of n2 and x must have the same type, which is quantified at the same level as 'a.
## 12 Using coercions Subtyping is never implicit. There are, however, two ways to perform subtyping. The most general construction is fully explicit: both the domain and the codomain of the type coercion must be given. We have seen that points and colored points have incompatible types. For instance, they cannot be mixed in the same list. However, a colored point can be coerced to a point, hiding its color method: ```ocaml # let colored_point_to_point cp = (cp : colored_point :> point);; val colored_point_to_point : colored_point -> point = \<fun\> # let p = new point 3 and q = new colored_point 4 "blue";; val p : point = \<obj> val q : colored_point = \<obj> # let l = \[p; (colored_point_to_point q)\];; val l : point list = \[\<obj>; \<obj>\] ``` An object of type t can be seen as an object of type t' only if t is a subtype of t'. For instance, a point cannot be seen as a colored point. ```ocaml # (p : point :> colored_point);; Error: Type point = \< get_offset : int; get_x : int; move : int -> unit \> is not a subtype of colored_point = \< color : string; get_offset : int; get_x : int; move : int -> unit \> The first object type has no method color ``` Indeed, narrowing coercions without runtime checks would be unsafe. Runtime type checks might raise exceptions, and they would require the presence of type information at runtime, which is not the case in the OCaml system. For these reasons, there is no such operation available in the language.
## 12 Using coercions Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types. For instance, the class of colored points could have been defined directly, without inheriting from the class of points; the type of colored points would remain unchanged and thus still be a subtype of points. The domain of a coercion can often be omitted. For instance, one can define: ```ocaml # let to_point cp = (cp :> point);; val to_point : #point -> point = \<fun\> ``` In this case, the function colored_point_to_point is an instance of the function to_point. This is not always true, however. The fully explicit coercion is more precise and is sometimes unavoidable. Consider, for example, the following class: ```ocaml # class c0 = object method m = {\< \>} method n = 0 end;; ``` class c0 : object ('a) method m : 'a method n : int end The object type c0 is an abbreviation for \<m : 'a; n : int> as 'a. Consider now the type declaration: ```ocaml # class type c1 = object method m : c1 end;; ``` class type c1 = object method m : c1 end The object type c1 is an abbreviation for the type \<m : 'a> as 'a. The coercion from an object of type c0 to an object of type c1 is correct: ```ocaml # fun (x:c0) -> (x : c0 :> c1);; - : c0 -> c1 = \<fun\> ``` However, the domain of the coercion cannot always be omitted. In that case, the solution is to use the explicit form. Sometimes, a change in the class-type definition can also solve the problem
## 12 Using coercions ```ocaml # class type c2 = object ('a) method m : 'a end;; ``` class type c2 = object ('a) method m : 'a end ```ocaml # fun (x:c0) -> (x :> c2);; - : c0 -> c2 = \<fun\> ``` While class types c1 and c2 are different, both object types c1 and c2 expand to the same object type (same method names and types). Yet, when the domain of a coercion is left implicit and its co-domain is an abbreviation of a known class type, then the class type, rather than the object type, is used to derive the coercion function. This allows leaving the domain implicit in most cases when coercing from a subclass to its superclass. The type of a coercion can always be seen as below: ```ocaml # let to_c1 x = (x :> c1);; val to_c1 : \< m : #c1; .. \> -> c1 = \<fun\> # let to_c2 x = (x :> c2);; val to_c2 : #c2 -> c2 = \<fun\> ```
## 12 Using coercions Note the difference between these two coercions: in the case of to_c2, the type #c2 = \< m : 'a; .. \> as 'a is polymorphically recursive (according to the explicit recursion in the class type of c2); hence the success of applying this coercion to an object of class c0. On the other hand, in the first case, c1 was only expanded and unrolled twice to obtain \< m : \< m : c1; .. \>; .. \> (remember #c1 = \< m : c1; .. \>), without introducing recursion. You may also note that the type of to_c2 is #c2 -> c2 while the type of to_c1 is more general than #c1 -> c1. This is not always true, since there are class types for which some instances of #c are not subtypes of c, as explained in section ‍[3.16](#s%3Abinary-methods). Yet, for parameterless classes the coercion (\_ :> c) is always more general than (\_ : #c :> c). A common problem may occur when one tries to define a coercion to a class c while defining class c. The problem is due to the type abbreviation not being completely defined yet, and so its subtypes are not clearly known. Then, a coercion (\_ :> c) or (\_ : #c :> c) is taken to be the identity function, as in ```ocaml # fun x -> (x :> 'a);; - : 'a -> 'a = \<fun\> ```
## 12 Using coercions As a consequence, if the coercion is applied to self, as in the following example, the type of self is unified with the closed type c (a closed object type is an object type without ellipsis). This would constrain the type of self be closed and is thus rejected. Indeed, the type of self cannot be closed: this would prevent any further extension of the class. Therefore, a type error is generated when the unification of this type with another type would result in a closed object type. ```ocaml # class c = object method m = 1 end and d = object (self) inherit c method n = 2 method as_c = (self :> c) end;; Error: This expression cannot be coerced to type c = \< m : int \>; it has type \< as_c : c; m : int; n : int; .. \> but is here used with type c Self type cannot escape its class ``` However, the most common instance of this problem, coercing self to its current class, is detected as a special case by the type checker, and properly typed. ```ocaml # class c = object (self) method m = (self :> c) end;; ``` class c : object method m : c end This allows the following idiom, keeping a list of all objects belonging to a class or its subclasses: ```ocaml # let all_c = ref \[\];; val all_c : '\_weak3 list ref = {contents = \[\]} # class c (m : int) = object (self) method m = m initializer all_c := (self :> c) :: !all_c end;; ``` class c : int -> object method m : int end This idiom can in turn be used to retrieve an object whose type has been weakened:
## 12 Using coercions ```ocaml # let rec lookup_obj obj = function \[\] -> raise Not_found \| obj' :: l -> if (obj :> \< \>) = (obj' :> \< \>) then obj' else lookup_obj obj l ;; val lookup_obj : \< .. \> -> (\< .. \> as 'a) list -> 'a = \<fun\> # let lookup_c obj = lookup_obj obj !all_c;; val lookup_c : \< .. \> -> \< m : int \> = \<fun\> ``` The type \< m : int \> we see here is just the expansion of c, due to the use of a reference; we have succeeded in getting back an object of type c. The previous coercion problem can often be avoided by first defining the abbreviation, using a class type: ```ocaml # class type c' = object method m : int end;; ``` class type c' = object method m : int end ```ocaml # class c : c' = object method m = 1 end and d = object (self) inherit c method n = 2 method as_c = (self :> c') end;; ``` class c : c' and d : object method as_c : c' method m : int method n : int end It is also possible to use a virtual class. Inheriting from this class simultaneously forces all methods of c to have the same type as the methods of c'. ```ocaml # class virtual c' = object method virtual m : int end;; ``` class virtual c' : object method virtual m : int end ```ocaml # class c = object (self) inherit c' method m = 1 end;; ``` class c : object method m : int end One could think of defining the type abbreviation directly: ```ocaml # type c' = \<m : int>;; ```
## 12 Using coercions However, the abbreviation #c' cannot be defined directly in a similar way. It can only be defined by a class or a class-type definition. This is because a #-abbreviation carries an implicit anonymous variable .. that cannot be explicitly named. The closer you get to it is: ```ocaml # type 'a c'\_class = 'a constraint 'a = \< m : int; .. \>;; ``` with an extra type variable capturing the open object type.
## 13 Functional objects It is possible to write a version of class point without assignments on the instance variables. The override construct {\< ... \>} returns a copy of “self” (that is, the current object), possibly changing the value of some instance variables. ```ocaml # class functional_point y = object val x = y method get_x = x method move d = {\< x = x + d \>} method move_to x = {\< x \>} end;; ``` class functional_point : int -> object ('a) val x : int method get_x : int method move : int -> 'a method move_to : int -> 'a end ```ocaml # let p = new functional_point 7;; val p : functional_point = \<obj> # p#get_x;; - : int = 7 # (p#move 3)#get_x;; - : int = 10 # (p#move_to 15)#get_x;; - : int = 15 # p#get_x;; - : int = 7 ``` As with records, the form {\< x \>} is an elided version of {\< x = x \>} which avoids the repetition of the instance variable name. Note that the type abbreviation functional_point is recursive, which can be seen in the class type of functional_point: the type of self is 'a and 'a appears inside the type of the method move. The above definition of functional_point is not equivalent to the following: ```ocaml # class bad_functional_point y = object val x = y method get_x = x method move d = new bad_functional_point (x+d) method move_to x = new bad_functional_point x end;; ``` class bad_functional_point : int -> object val x : int method get_x : int method move : int -> bad_functional_point method move_to : int -> bad_functional_point end
## 13 Functional objects While objects of either class will behave the same, objects of their subclasses will be different. In a subclass of bad_functional_point, the method move will keep returning an object of the parent class. On the contrary, in a subclass of functional_point, the method move will return an object of the subclass. Functional update is often used in conjunction with binary methods as illustrated in section ‍[8.2.1](advexamples.html#ss%3Astring-as-class).
## 14 Cloning objects Objects can also be cloned, whether they are functional or imperative. The library function Oo.copy makes a shallow copy of an object. That is, it returns a new object that has the same methods and instance variables as its argument. The instance variables are copied but their contents are shared. Assigning a new value to an instance variable of the copy (using a method call) will not affect instance variables of the original, and conversely. A deeper assignment (for example if the instance variable is a reference cell) will of course affect both the original and the copy. The type of Oo.copy is the following: ```ocaml # Oo.copy;; - : (\< .. \> as 'a) -> 'a = \<fun\> ``` The keyword as in that type binds the type variable 'a to the object type \< .. \>. Therefore, Oo.copy takes an object with any methods (represented by the ellipsis), and returns an object of the same type. The type of Oo.copy is different from type \< .. \> -> \< .. \> as each ellipsis represents a different set of methods. Ellipsis actually behaves as a type variable. ```ocaml # let p = new point 5;; val p : point = \<obj> # let q = Oo.copy p;; val q : point = \<obj> # q#move 7; (p#get_x, q#get_x);; - : int \* int = (5, 12) ``` In fact, Oo.copy p will behave as p#copy assuming that a public method copy with body {\< \>} has been defined in the class of p. Objects can be compared using the generic comparison functions = and \<\>. Two objects are equal if and only if they are physically equal. In particular, an object and its copy are not equal.
## 14 Cloning objects ```ocaml # let q = Oo.copy p;; val q : point = \<obj> # p = q, p = p;; - : bool \* bool = (false, true) ``` Other generic comparisons such as (\<, \<=, ...) can also be used on objects. The relation \< defines an unspecified but strict ordering on objects. The ordering relationship between two objects is fixed permanently once the two objects have been created, and it is not affected by mutation of fields. Cloning and override have a non empty intersection. They are interchangeable when used within an object and without overriding any field: ```ocaml # class copy = object method copy = {\< \>} end;; ``` class copy : object ('a) method copy : 'a end ```ocaml # class copy = object (self) method copy = Oo.copy self end;; ``` class copy : object ('a) method copy : 'a end Only the override can be used to actually override fields, and only the Oo.copy primitive can be used externally. Cloning can also be used to provide facilities for saving and restoring the state of objects. ```ocaml # class backup = object (self : 'mytype) val mutable copy = None method save = copy \<- Some {\< copy = None \>} method restore = match copy with Some x -> x \| None -> self end;; ``` class backup : object ('a) val mutable copy : 'a option method restore : 'a method save : unit end The above definition will only backup one level. The backup facility can be added to any class by using multiple inheritance. ```ocaml # class \['a\] backup_ref x = object inherit \['a\] oref x inherit backup end;; ```
## 14 Cloning objects class \['a\] backup_ref : 'a -> object ('b) val mutable copy : 'b option val mutable x : 'a method get : 'a method restore : 'b method save : unit method set : 'a -> unit end ```ocaml # let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);; val get : (\< get : 'b; restore : 'a; .. \> as 'a) -> int -> 'b = \<fun\> # let p = new backup_ref 0 in p # save; p # set 1; p # save; p # set 2; \[get p 0; get p 1; get p 2; get p 3; get p 4\];; - : int list = \[2; 1; 1; 1; 1\] ``` We can define a variant of backup that retains all copies. (We also add a method clear to manually erase all copies.) ```ocaml # class backup = object (self : 'mytype) val mutable copy = None method save = copy \<- Some {\< \>} method restore = match copy with Some x -> x \| None -> self method clear = copy \<- None end;; ``` class backup : object ('a) val mutable copy : 'a option method clear : unit method restore : 'a method save : unit end ```ocaml # class \['a\] backup_ref x = object inherit \['a\] oref x inherit backup end;; ``` class \['a\] backup_ref : 'a -> object ('b) val mutable copy : 'b option val mutable x : 'a method clear : unit method get : 'a method restore : 'b method save : unit method set : 'a -> unit end ```ocaml # let p = new backup_ref 0 in p # save; p # set 1; p # save; p # set 2; \[get p 0; get p 1; get p 2; get p 3; get p 4\];; - : int list = \[2; 1; 0; 0; 0\] ```
## 15 Recursive classes Recursive classes can be used to define objects whose types are mutually recursive. ```ocaml # class window = object val mutable top_widget = (None : widget option) method top_widget = top_widget end and widget (w : window) = object val window = w method window = window end;; ``` class window : object val mutable top_widget : widget option method top_widget : widget option end and widget : window -> object val window : window method window : window end Although their types are mutually recursive, the classes widget and window are themselves independent.
## 16 Binary methods A binary method is a method which takes an argument of the same type as self. The class comparable below is a template for classes with a binary method leq of type 'a -> bool where the type variable 'a is bound to the type of self. Therefore, #comparable expands to \< leq : 'a -> bool; .. \> as 'a. We see here that the binder as also allows writing recursive types. ```ocaml # class virtual comparable = object (\_ : 'a) method virtual leq : 'a -> bool end;; ``` class virtual comparable : object ('a) method virtual leq : 'a -> bool end We then define a subclass money of comparable. The class money simply wraps floats as comparable objects.<sup>[1](#note1)</sup> We will extend money below with more operations. We have to use a type constraint on the class parameter x because the primitive \<= is a polymorphic function in OCaml. The inherit clause ensures that the type of objects of this class is an instance of #comparable. ```ocaml # class money (x : float) = object inherit comparable val repr = x method value = repr method leq p = repr \<= p#value end;; ``` class money : float -> object ('a) val repr : float method leq : 'a -> bool method value : float end
## 16 Binary methods Note that the type money is not a subtype of type comparable, as the self type appears in contravariant position in the type of method leq. Indeed, an object m of class money has a method leq that expects an argument of type money since it accesses its value method. Considering m of type comparable would allow a call to method leq on m with an argument that does not have a method value, which would be an error. Similarly, the type money2 below is not a subtype of type money. ```ocaml # class money2 x = object inherit money x method times k = {\< repr = k \*. repr \>} end;; ``` class money2 : float -> object ('a) val repr : float method leq : 'a -> bool method times : float -> 'a method value : float end It is however possible to define functions that manipulate objects of type either money or money2: the function min will return the minimum of any two objects whose type unifies with #comparable. The type of min is not the same as #comparable -> #comparable -> #comparable, as the abbreviation #comparable hides a type variable (an ellipsis). Each occurrence of this abbreviation generates a new variable. ```ocaml # let min (x : #comparable) y = if x#leq y then x else y;; val min : (#comparable as 'a) -> 'a -> 'a = \<fun\> ``` This function can be applied to objects of type money or money2. ```ocaml # (min (new money 1.3) (new money 3.1))#value;; - : float = 1.3 # (min (new money2 5.0) (new money2 3.14))#value;; - : float = 3.14 ```
## 16 Binary methods More examples of binary methods can be found in sections ‍[8.2.1](advexamples.html#ss%3Astring-as-class) and ‍[8.2.3](advexamples.html#ss%3Aset-as-class). Note the use of override for method times. Writing new money2 (k \*. repr) instead of {\< repr = k \*. repr \>} would not behave well with inheritance: in a subclass money3 of money2 the times method would return an object of class money2 but not of class money3 as would be expected. The class money could naturally carry another binary method. Here is a direct definition: ```ocaml # class money x = object (self : 'a) val repr = x method value = repr method print = print_float repr method times k = {\< repr = k \*. x \>} method leq (p : 'a) = repr \<= p#value method plus (p : 'a) = {\< repr = x +. p#value \>} end;; ``` class money : float -> object ('a) val repr : float method leq : 'a -> bool method plus : 'a -> 'a method print : unit method times : float -> 'a method value : float end
## 17 Friends The above class money reveals a problem that often occurs with binary methods. In order to interact with other objects of the same class, the representation of money objects must be revealed, using a method such as value. If we remove all binary methods (here plus and leq), the representation can easily be hidden inside objects by removing the method value as well. However, this is not possible as soon as some binary method requires access to the representation of objects of the same class (other than self). ```ocaml # class safe_money x = object (self : 'a) val repr = x method print = print_float repr method times k = {\< repr = k \*. x \>} end;; ``` class safe_money : float -> object ('a) val repr : float method print : unit method times : float -> 'a end Here, the representation of the object is known only to a particular object. To make it available to other objects of the same class, we are forced to make it available to the whole world. However we can easily restrict the visibility of the representation using the module system. ```ocaml # module type MONEY = sig type t class c : float -> object ('a) val repr : t method value : t method print : unit method times : float -> 'a method leq : 'a -> bool method plus : 'a -> 'a end end;; # module Euro : MONEY = struct type t = float class c x = object (self : 'a) val repr = x method value = repr method print = print_float repr method times k = {\< repr = k \*. x \>} method leq (p : 'a) = repr \<= p#value method plus (p : 'a) = {\< repr = x +. p#value \>} end end;; ```
## 17 Friends Another example of friend functions may be found in section ‍[8.2.3](advexamples.html#ss%3Aset-as-class). These examples occur when a group of objects (here objects of the same class) and functions should see each others internal representation, while their representation should be hidden from the outside. The solution is always to define all friends in the same module, give access to the representation and use a signature constraint to make the representation abstract outside the module. ------------------------------------------------------------------------ [1](#text1) floats are an approximation of decimal numbers, they are unsuitable for use in most monetary calculations as they may introduce errors. ------------------------------------------------------------------------ [« The module system](moduleexamples.html)[Labeled arguments »](lablexamples.html) (Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Labeled arguments Source: https://ocaml.org/manual/5.2/lablexamples.html ☰ - [The core language](coreexamples.html) - [The module system](moduleexamples.html) - [Objects in OCaml](objectexamples.html) - [Labeled arguments](lablexamples.html) - [Polymorphic variants](polyvariant.html) - [Polymorphism and its limitations](polymorphism.html) - [Generalized algebraic datatypes](gadts-tutorial.html) - [Advanced examples with classes and modules](advexamples.html) - [Parallel programming](parallelism.html) - [Memory model: The hard bits](memorymodel.html)
End of preview. Expand in Data Studio

Ocaml Programming Language Documentation

This dataset contains the Ocaml programming language documentation, chunked using semantic parsing for pretraining language models.

Updated: 2025-09-08

Loading

from datasets import load_dataset
ds = load_dataset("json", data_files={"train": "train.jsonl"}, split="train")

Statistics

  • Format: JSONL with single text field per line
  • Chunking: Semantic structure-aware chunking
  • Content: Official Ocaml documentation and manuals
Downloads last month
100

Collection including jusjinuk/ocaml-manuals