text
stringlengths 10
16.2k
|
---|
# Chapter 4 Labeled arguments
If you have a look at modules ending in Labels in the standard library, you will see that function types have annotations you did not have in the functions you defined yourself.
```ocaml
# ListLabels.map;;
- : f:('a -> 'b) -> 'a list -> 'b list = \<fun\>
# StringLabels.sub;;
- : string -> pos:int -> len:int -> string = \<fun\>
```
Such annotations of the form name: are called *labels*. They are meant to document the code, allow more checking, and give more flexibility to function application. You can give such names to arguments in your programs, by prefixing them with a tilde \~.
```ocaml
# let f \~x \~y = x - y;;
val f : x:int -> y:int -> int = \<fun\>
# let x = 3 and y = 2 in f \~x \~y;;
- : int = 1
```
When you want to use distinct names for the variable and the label appearing in the type, you can use a naming label of the form \~name:. This also applies when the argument is not a variable.
```ocaml
# let f \~x:x1 \~y:y1 = x1 - y1;;
val f : x:int -> y:int -> int = \<fun\>
# f \~x:3 \~y:2;;
- : int = 1
```
Labels obey the same rules as other identifiers in OCaml, that is you cannot use a reserved keyword (like in or to) as a label.
Formal parameters and arguments are matched according to their respective labels, the absence of label being interpreted as the empty label. This allows commuting arguments in applications. One can also partially apply a function on any argument, creating a new function of the remaining parameters.
|
# Chapter 4 Labeled arguments
```ocaml
# let f \~x \~y = x - y;;
val f : x:int -> y:int -> int = \<fun\>
# f \~y:2 \~x:3;;
- : int = 1
# ListLabels.fold_left;;
- : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc = \<fun\>
# ListLabels.fold_left \[1;2;3\] \~init:0 \~f:( + );;
- : int = 6
# ListLabels.fold_left \~init:0;;
- : f:(int -> 'a -> int) -> 'a list -> int = \<fun\>
```
If several arguments of a function bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.
```ocaml
# let hline \~x:x1 \~x:x2 \~y = (x1, x2, y);;
val hline : x:'a -> x:'b -> y:'c -> 'a \* 'b \* 'c = \<fun\>
# hline \~x:3 \~y:2 \~x:5;;
- : int \* int \* int = (3, 5, 2)
```
|
## 1 Optional arguments
An interesting feature of labeled arguments is that they can be made optional. For optional parameters, the question mark ? replaces the tilde \~ of non-optional ones, and the label is also prefixed by ? in the function type. Default values may be given for such optional parameters.
```ocaml
# let bump ?(step = 1) x = x + step;;
val bump : ?step:int -> int -> int = \<fun\>
# bump 2;;
- : int = 3
# bump \~step:3 2;;
- : int = 5
```
A function taking some optional arguments must also take at least one non-optional argument. The criterion for deciding whether an optional argument has been omitted is the non-labeled application of an argument appearing after this optional argument in the function type. Note that if that argument is labeled, you will only be able to eliminate optional arguments by totally applying the function, omitting all optional arguments and omitting all labels for all remaining arguments.
```ocaml
# let test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);;
val test : ?x:int -> ?y:int -> unit -> ?z:int -> unit -> int \* int \* int = \<fun\>
# test ();;
- : ?z:int -> unit -> int \* int \* int = \<fun\>
# test \~x:2 () \~z:3 ();;
- : int \* int \* int = (2, 0, 3)
```
Optional parameters may also commute with non-optional or unlabeled ones, as long as they are applied simultaneously. By nature, optional arguments do not commute with unlabeled arguments applied independently.
|
## 1 Optional arguments
```ocaml
# test \~y:2 \~x:3 () ();;
- : int \* int \* int = (3, 2, 0)
# test () () \~z:1 \~y:2 \~x:3;;
- : int \* int \* int = (3, 2, 1)
# (test () ()) \~z:1 ;;
Error: This expression has type int \* int \* int This is not a function; it cannot be applied.
```
Here (test () ()) is already (0,0,0) and cannot be further applied.
Optional arguments are actually implemented as option types. If you do not give a default value, you have access to their internal representation, type 'a option = None \| Some of 'a. You can then provide different behaviors when an argument is present or not.
```ocaml
# let bump ?step x = match step with \| None -> x \* 2 \| Some y -> x + y ;;
val bump : ?step:int -> int -> int = \<fun\>
```
It may also be useful to relay an optional argument from a function call to another. This can be done by prefixing the applied argument with ?. This question mark disables the wrapping of optional argument in an option type.
```ocaml
# let test2 ?x ?y () = test ?x ?y () ();;
val test2 : ?x:int -> ?y:int -> unit -> int \* int \* int = \<fun\>
# test2 ?x:None;;
- : ?y:int -> unit -> int \* int \* int = \<fun\>
```
|
## 2 Labels and type inference
While they provide an increased comfort for writing function applications, labels and optional arguments have the pitfall that they cannot be inferred as completely as the rest of the language.
You can see it in the following two examples.
```ocaml
# let h' g = g \~y:2 \~x:3;;
val h' : (y:int -> x:int -> 'a) -> 'a = \<fun\>
# h' f ;;
Error: This expression has type x:int -> y:int -> int but an expression was expected of type y:int -> x:int -> 'a
# let bump_it bump x = bump \~step:2 x;;
val bump_it : (step:int -> 'a -> 'b) -> 'a -> 'b = \<fun\>
# bump_it bump 1 ;;
Error: This expression has type ?step:int -> int -> int but an expression was expected of type step:int -> 'a -> 'b
```
The first case is simple: g is passed \~y and then \~x, but f expects \~x and then \~y. This is correctly handled if we know the type of g to be x:int -> y:int -> int in advance, but otherwise this causes the above type clash. The simplest workaround is to apply formal parameters in a standard order.
The second example is more subtle: while we intended the argument bump to be of type ?step:int -> int -> int, it is inferred as step:int -> int -> 'a. These two types being incompatible (internally normal and optional arguments are different), a type error occurs when applying bump_it to the real bump.
|
## 2 Labels and type inference
We will not try here to explain in detail how type inference works. One must just understand that there is not enough information in the above program to deduce the correct type of g or bump. That is, there is no way to know whether an argument is optional or not, or which is the correct order, by looking only at how a function is applied. The strategy used by the compiler is to assume that there are no optional arguments, and that applications are done in the right order.
The right way to solve this problem for optional parameters is to add a type annotation to the argument bump.
```ocaml
# let bump_it (bump : ?step:int -> int -> int) x = bump \~step:2 x;;
val bump_it : (?step:int -> int -> int) -> int -> int = \<fun\>
# bump_it bump 1;;
- : int = 3
```
In practice, such problems appear mostly when using objects whose methods have optional arguments, so writing the type of object arguments is often a good idea.
Normally the compiler generates a type error if you attempt to pass to a function a parameter whose type is different from the expected one. However, in the specific case where the expected type is a non-labeled function type, and the argument is a function expecting optional parameters, the compiler will attempt to transform the argument to have it match the expected type, by passing None for all optional parameters.
```ocaml
# let twice f (x : int) = f(f x);;
val twice : (int -> int) -> int -> int = \<fun\>
# twice bump 2;;
- : int = 8
```
|
## 2 Labels and type inference
This transformation is coherent with the intended semantics, including side-effects. That is, if the application of optional parameters shall produce side-effects, these are delayed until the received function is really applied to an argument.
|
## 3 Suggestions for labeling
Like for names, choosing labels for functions is not an easy task. A good labeling is one which
- makes programs more readable,
- is easy to remember,
- when possible, allows useful partial applications.
We explain here the rules we applied when labeling OCaml libraries.
To speak in an “object-oriented” way, one can consider that each function has a main argument, its *object*, and other arguments related with its action, the *parameters*. To permit the combination of functions through functionals in commuting label mode, the object will not be labeled. Its role is clear from the function itself. The parameters are labeled with names reminding of their nature or their role. The best labels combine nature and role. When this is not possible the role is to be preferred, since the nature will often be given by the type itself. Obscure abbreviations should be avoided.
ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list
UnixLabels.write : file_descr -> buf:bytes -> pos:int -> len:int -> unit
When there are several objects of same nature and role, they are all left unlabeled.
ListLabels.iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
When there is no preferable object, all arguments are labeled.
BytesLabels.blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
However, when there is only one argument, it is often left unlabeled.
BytesLabels.create : int -> bytes
|
## 3 Suggestions for labeling
This principle also applies to functions of several arguments whose return type is a type variable, as long as the role of each argument is not ambiguous. Labeling such functions may lead to awkward error messages when one attempts to omit labels in an application, as we have seen with ListLabels.fold_left.
Here are some of the label names you will find throughout the libraries.
| | |
|-----------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
| Label | Meaning |
| f: | a function to be applied |
| pos: | a position in a string, array or byte sequence |
| len: | a length |
| buf: | a byte sequence or string used as buffer |
| src: | the source of an operation |
| dst: | the destination of an operation |
| init: | the initial value for an iterator |
| cmp: | a comparison function, e.g. Stdlib.compare |
| mode: | an operation mode or a flag list |
|
## 3 Suggestions for labeling
All these are only suggestions, but keep in mind that the choice of labels is essential for readability. Bizarre choices will make the program harder to maintain.
In the ideal, the right function name with right labels should be enough to understand the function’s meaning. Since one can get this information with OCamlBrowser or the ocaml toplevel, the documentation is only used when a more detailed specification is needed.
------------------------------------------------------------------------
[« Objects in OCaml](objectexamples.html)[Polymorphic variants »](polyvariant.html)
(Chapter written by Jacques Garrigue)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Polymorphic variants
Source: https://ocaml.org/manual/5.2/polyvariant.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 5 Polymorphic variants
Variants as presented in section [1.4](coreexamples.html#s%3Atut-recvariants) are a powerful tool to build data structures and algorithms. However they sometimes lack flexibility when used in modular programming. This is due to the fact that every constructor is assigned to a unique type when defined and used. Even if the same name appears in the definition of multiple types, the constructor itself belongs to only one type. Therefore, one cannot decide that a given constructor belongs to multiple types, or consider a value of some type to belong to some other type with more constructors.
With polymorphic variants, this original assumption is removed. That is, a variant tag does not belong to any type in particular, the type system will just check that it is an admissible value according to its use. You need not define a type before using a variant tag. A variant type will be inferred independently for each of its uses.
|
## 1 Basic use
In programs, polymorphic variants work like usual ones. You just have to prefix their names with a backquote character \`.
```ocaml
# \[\`On; \`Off\];;
- : \[\> \`Off \| \`On \] list = \[\`On; \`Off\]
# \`Number 1;;
- : \[\> \`Number of int \] = \`Number 1
# let f = function \`On -> 1 \| \`Off -> 0 \| \`Number n -> n;;
val f : \[\< \`Number of int \| \`Off \| \`On \] -> int = \<fun\>
# List.map f \[\`On; \`Off\];;
- : int list = \[1; 0\]
```
\[\>\`Off\|\`On\] list means that to match this list, you should at least be able to match \`Off and \`On, without argument. \[\<\`On\|\`Off\|\`Number of int\] means that f may be applied to \`Off, \`On (both without argument), or \`Number n where n is an integer. The \> and \< inside the variant types show that they may still be refined, either by defining more tags or by allowing less. As such, they contain an implicit type variable. Because each of the variant types appears only once in the whole type, their implicit type variables are not shown.
The above variant types were polymorphic, allowing further refinement. When writing type annotations, one will most often describe fixed variant types, that is types that cannot be refined. This is also the case for type abbreviations. Such types do not contain \< or \>, but just an enumeration of the tags and their associated types, just like in a normal datatype definition.
|
## 1 Basic use
```ocaml
# type 'a vlist = \[\`Nil \| \`Cons of 'a \* 'a vlist\];;
type 'a vlist = \[ \`Cons of 'a \* 'a vlist \| \`Nil \]
# let rec map f : 'a vlist -> 'b vlist = function \| \`Nil -> \`Nil \| \`Cons(a, l) -> \`Cons(f a, map f l) ;;
val map : ('a -> 'b) -> 'a vlist -> 'b vlist = \<fun\>
```
|
## 2 Advanced use
Type-checking polymorphic variants is a subtle thing, and some expressions may result in more complex type information.
```ocaml
# let f = function \`A -> \`C \| \`B -> \`D \| x -> x;;
val f : (\[\> \`A \| \`B \| \`C \| \`D \] as 'a) -> 'a = \<fun\>
# f \`E;;
- : \[\> \`A \| \`B \| \`C \| \`D \| \`E \] = \`E
```
Here we are seeing two phenomena. First, since this matching is open (the last case catches any tag), we obtain the type \[\> \`A \| \`B\] rather than \[\< \`A \| \`B\] in a closed matching. Then, since x is returned as is, input and return types are identical. The notation as 'a denotes such type sharing. If we apply f to yet another tag \`E, it gets added to the list.
```ocaml
# let f1 = function \`A x -> x = 1 \| \`B -> true \| \`C -> false let f2 = function \`A x -> x = "a" \| \`B -> true ;;
val f1 : \[\< \`A of int \| \`B \| \`C \] -> bool = \<fun\> val f2 : \[\< \`A of string \| \`B \] -> bool = \<fun\>
# let f x = f1 x && f2 x;;
val f : \[\< \`A of string & int \| \`B \] -> bool = \<fun\>
```
Here f1 and f2 both accept the variant tags \`A and \`B, but the argument of \`A is int for f1 and string for f2. In f’s type \`C, only accepted by f1, disappears, but both argument types appear for \`A as int & string. This means that if we pass the variant tag \`A to f, its argument should be *both* int and string. Since there is no such value, f cannot be applied to \`A, and \`B is the only accepted input.
|
## 2 Advanced use
Even if a value has a fixed variant type, one can still give it a larger type through coercions. Coercions are normally written with both the source type and the destination type, but in simple cases the source type may be omitted.
```ocaml
# type 'a wlist = \[\`Nil \| \`Cons of 'a \* 'a wlist \| \`Snoc of 'a wlist \* 'a\];;
type 'a wlist = \[ \`Cons of 'a \* 'a wlist \| \`Nil \| \`Snoc of 'a wlist \* 'a \]
# let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);;
val wlist_of_vlist : 'a vlist -> 'a wlist = \<fun\>
# let open_vlist l = (l : 'a vlist :> \[\> 'a vlist\]);;
val open_vlist : 'a vlist -> \[\> 'a vlist \] = \<fun\>
# fun x -> (x :> \[\`A\|\`B\|\`C\]);;
- : \[\< \`A \| \`B \| \`C \] -> \[ \`A \| \`B \| \`C \] = \<fun\>
```
You may also selectively coerce values through pattern matching.
```ocaml
# let split_cases = function \| \`Nil \| \`Cons \_ as x -> \`A x \| \`Snoc \_ as x -> \`B x ;;
val split_cases : \[\< \`Cons of 'a \| \`Nil \| \`Snoc of 'b \] -> \[\> \`A of \[\> \`Cons of 'a \| \`Nil \] \| \`B of \[\> \`Snoc of 'b \] \] = \<fun\>
```
When an or-pattern composed of variant tags is wrapped inside an alias-pattern, the alias is given a type containing only the tags enumerated in the or-pattern. This allows for many useful idioms, like incremental definition of functions.
|
## 2 Advanced use
```ocaml
# let num x = \`Num x let eval1 eval (\`Num x) = x let rec eval x = eval1 eval x ;;
val num : 'a -> \[\> \`Num of 'a \] = \<fun\> val eval1 : 'a -> \[\< \`Num of 'b \] -> 'b = \<fun\> val eval : \[\< \`Num of 'a \] -> 'a = \<fun\>
# let plus x y = \`Plus(x,y) let eval2 eval = function \| \`Plus(x,y) -> eval x + eval y \| \`Num \_ as x -> eval1 eval x let rec eval x = eval2 eval x ;;
val plus : 'a -> 'b -> \[\> \`Plus of 'a \* 'b \] = \<fun\> val eval2 : ('a -> int) -> \[\< \`Num of int \| \`Plus of 'a \* 'a \] -> int = \<fun\> val eval : (\[\< \`Num of int \| \`Plus of 'a \* 'a \] as 'a) -> int = \<fun\>
```
To make this even more comfortable, you may use type definitions as abbreviations for or-patterns. That is, if you have defined type myvariant = \[\`Tag1 of int \| \`Tag2 of bool\], then the pattern #myvariant is equivalent to writing (\`Tag1(\_ : int) \| \`Tag2(\_ : bool)).
Such abbreviations may be used alone,
```ocaml
# let f = function \| #myvariant -> "myvariant" \| \`Tag3 -> "Tag3";;
val f : \[\< \`Tag1 of int \| \`Tag2 of bool \| \`Tag3 \] -> string = \<fun\>
```
or combined with with aliases.
```ocaml
# let g1 = function \`Tag1 \_ -> "Tag1" \| \`Tag2 \_ -> "Tag2";;
val g1 : \[\< \`Tag1 of 'a \| \`Tag2 of 'b \] -> string = \<fun\>
# let g = function \| #myvariant as x -> g1 x \| \`Tag3 -> "Tag3";;
val g : \[\< \`Tag1 of int \| \`Tag2 of bool \| \`Tag3 \] -> string = \<fun\>
```
|
## 3 Weaknesses of polymorphic variants
After seeing the power of polymorphic variants, one may wonder why they were added to core language variants, rather than replacing them.
The answer is twofold. The first aspect is that while being pretty efficient, the lack of static type information allows for less optimizations, and makes polymorphic variants slightly heavier than core language ones. However noticeable differences would only appear on huge data structures.
More important is the fact that polymorphic variants, while being type-safe, result in a weaker type discipline. That is, core language variants do actually much more than ensuring type-safety, they also check that you use only declared constructors, that all constructors present in a data-structure are compatible, and they enforce typing constraints to their parameters.
For this reason, you must be more careful about making types explicit when you use polymorphic variants. When you write a library, this is easy since you can describe exact types in interfaces, but for simple programs you are probably better off with core language variants.
Beware also that some idioms make trivial errors very hard to find. For instance, the following code is probably wrong but the compiler has no way to see it.
```ocaml
# type abc = \[\`A \| \`B \| \`C\] ;;
type abc = \[ \`A \| \`B \| \`C \]
# let f = function \| \`As -> "A" \| #abc -> "other" ;;
val f : \[\< \`A \| \`As \| \`B \| \`C \] -> string = \<fun\>
# let f : abc -> string = f ;;
val f : abc -> string = \<fun\>
```
|
## 3 Weaknesses of polymorphic variants
You can avoid such risks by annotating the definition itself.
```ocaml
# let f : abc -> string = function \| \`As -> "A" \| #abc -> "other" ;;
Error: This pattern matches values of type \[? \`As \] but a pattern was expected which matches values of type abc The second variant type does not allow tag(s) \`As
```
------------------------------------------------------------------------
[« Labeled arguments](lablexamples.html)[Polymorphism and its limitations »](polymorphism.html)
(Chapter written by Jacques Garrigue)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Polymorphism and its limitations
Source: https://ocaml.org/manual/5.2/polymorphism.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 6 Polymorphism and its limitations
This chapter covers more advanced questions related to the limitations of polymorphic functions and types. There are some situations in OCaml where the type inferred by the type checker may be less generic than expected. Such non-genericity can stem either from interactions between side-effects and typing or the difficulties of implicit polymorphic recursion and higher-rank polymorphism.
This chapter details each of these situations and, if it is possible, how to recover genericity.
|
## 1 Weak polymorphism and mutation
|
### 1.1 Weakly polymorphic types
Maybe the most frequent examples of non-genericity derive from the interactions between polymorphic types and mutation. A simple example appears when typing the following expression
```ocaml
# let store = ref None ;;
val store : '\_weak1 option ref = {contents = None}
```
Since the type of None is 'a option and the function ref has type 'b -> 'b ref, a natural deduction for the type of store would be 'a option ref. However, the inferred type, '\_weak1 option ref, is different. Type variables whose names start with a \_weak prefix like '\_weak1 are weakly polymorphic type variables, sometimes shortened to “weak type variables”. A weak type variable is a placeholder for a single type that is currently unknown. Once the specific type t behind the placeholder type '\_weak1 is known, all occurrences of '\_weak1 will be replaced by t. For instance, we can define another option reference and store an int inside:
```ocaml
# let another_store = ref None ;;
val another_store : '\_weak2 option ref = {contents = None}
# another_store := Some 0; another_store ;;
- : int option ref = {contents = Some 0}
```
After storing an int inside another_store, the type of another_store has been updated from '\_weak2 option ref to int option ref. This distinction between weakly and generic polymorphic type variable protects OCaml programs from unsoundness and runtime errors. To understand from where unsoundness might come, consider this simple function which swaps a value x with the value stored inside a store reference, if there is such value:
|
### 1.1 Weakly polymorphic types
```ocaml
# let swap store x = match !store with \| None -> store := Some x; x \| Some y -> store := Some x; y;;
val swap : 'a option ref -> 'a -> 'a = \<fun\>
```
We can apply this function to our store
```ocaml
# let one = swap store 1 let one_again = swap store 2 let two = swap store 3;;
val one : int = 1 val one_again : int = 1 val two : int = 2
```
After these three swaps the stored value is 3. Everything is fine up to now. We can then try to swap 3 with a more interesting value, for instance a function:
```ocaml
# let error = swap store (fun x -> x);;
Error: This expression should not be a function, the expected type is int
```
At this point, the type checker rightfully complains that it is not possible to swap an integer and a function, and that an int should always be traded for another int. Furthermore, the type checker prevents us from manually changing the type of the value stored by store:
```ocaml
# store := Some (fun x -> x);;
Error: This expression should not be a function, the expected type is int
```
Indeed, looking at the type of store, we see that the weak type '\_weak1 has been replaced by the type int
```ocaml
# store;;
- : int option ref = {contents = Some 3}
```
Therefore, after placing an int in store, we cannot use it to store any value other than an int. More generally, weak types protect the program from undue mutation of values with a polymorphic type.
|
### 1.1 Weakly polymorphic types
Moreover, weak types cannot appear in the signature of toplevel modules: types must be known at compilation time. Otherwise, different compilation units could replace the weak type with different and incompatible types. For this reason, compiling the following small piece of code
let option_ref = ref None
yields a compilation error
Error: The type of this expression, '_weak1 option ref,
contains type variables that cannot be generalized
To solve this error, it is enough to add an explicit type annotation to specify the type at declaration time:
let option_ref: int option ref = ref None
This is in any case a good practice for such global mutable variables. Otherwise, they will pick out the type of first use. If there is a mistake at this point, it can result in confusing type errors when later, correct uses are flagged as errors.
|
### 1.2 The value restriction
Identifying the exact context in which polymorphic types should be replaced by weak types in a modular way is a difficult question. Indeed the type system must handle the possibility that functions may hide persistent mutable states. For instance, the following function uses an internal reference to implement a delayed identity function
```ocaml
# let make_fake_id () = let store = ref None in fun x -> swap store x ;;
val make_fake_id : unit -> 'a -> 'a = \<fun\>
# let fake_id = make_fake_id();;
val fake_id : '\_weak3 -> '\_weak3 = \<fun\>
```
It would be unsound to apply this fake_id function to values with different types. The function fake_id is therefore rightfully assigned the type '\_weak3 -> '\_weak3 rather than 'a -> 'a. At the same time, it ought to be possible to use a local mutable state without impacting the type of a function.
To circumvent these dual difficulties, the type checker considers that any value returned by a function might rely on persistent mutable states behind the scene and should be given a weak type. This restriction on the type of mutable values and the results of function application is called the value restriction. Note that this value restriction is conservative: there are situations where the value restriction is too cautious and gives a weak type to a value that could be safely generalized to a polymorphic type:
```ocaml
# let not_id = (fun x -> x) (fun x -> x);;
val not_id : '\_weak4 -> '\_weak4 = \<fun\>
```
|
### 1.2 The value restriction
Quite often, this happens when defining functions using higher order functions. To avoid this problem, a solution is to add an explicit argument to the function:
```ocaml
# let id_again = fun x -> (fun x -> x) (fun x -> x) x;;
val id_again : 'a -> 'a = \<fun\>
```
With this argument, id_again is seen as a function definition by the type checker and can therefore be generalized. This kind of manipulation is called eta-expansion in lambda calculus and is sometimes referred under this name.
|
### 1.3 The relaxed value restriction
There is another partial solution to the problem of unnecessary weak types, which is implemented directly within the type checker. Briefly, it is possible to prove that weak types that only appear as type parameters in covariant positions –also called positive positions– can be safely generalized to polymorphic types. For instance, the type 'a list is covariant in 'a:
```ocaml
# let f () = \[\];;
val f : unit -> 'a list = \<fun\>
# let empty = f ();;
val empty : 'a list = \[\]
```
Note that the type inferred for empty is 'a list and not the '\_weak5 list that should have occurred with the value restriction.
The value restriction combined with this generalization for covariant type parameters is called the relaxed value restriction.
|
### 1.4 Variance and value restriction
Variance describes how type constructors behave with respect to subtyping. Consider for instance a pair of type x and xy with x a subtype of xy, denoted x :> xy:
```ocaml
# type x = \[ \`X \];;
type x = \[ \`X \]
# type xy = \[ \`X \| \`Y \];;
type xy = \[ \`X \| \`Y \]
```
As x is a subtype of xy, we can convert a value of type x to a value of type xy:
```ocaml
# let x:x = \`X;;
val x : x = \`X
# let x' = ( x :> xy);;
val x' : xy = \`X
```
Similarly, if we have a value of type x list, we can convert it to a value of type xy list, since we could convert each element one by one:
```ocaml
# let l:x list = \[\`X; \`X\];;
val l : x list = \[\`X; \`X\]
# let l' = ( l :> xy list);;
val l' : xy list = \[\`X; \`X\]
```
In other words, x :> xy implies that x list :> xy list, therefore the type constructor 'a list is covariant (it preserves subtyping) in its parameter 'a.
Contrarily, if we have a function that can handle values of type xy
```ocaml
# let f: xy -> unit = function \| \`X -> () \| \`Y -> ();;
val f : xy -> unit = \<fun\>
```
it can also handle values of type x:
```ocaml
# let f' = (f :> x -> unit);;
val f' : x -> unit = \<fun\>
```
Note that we can rewrite the type of f and f' as
```ocaml
# type 'a proc = 'a -> unit let f' = (f: xy proc :> x proc);;
type 'a proc = 'a -> unit val f' : x proc = \<fun\>
```
|
### 1.4 Variance and value restriction
In this case, we have x :> xy implies xy proc :> x proc. Notice that the second subtyping relation reverse the order of x and xy: the type constructor 'a proc is contravariant in its parameter 'a. More generally, the function type constructor 'a -> 'b is covariant in its return type 'b and contravariant in its argument type 'a.
A type constructor can also be invariant in some of its type parameters, neither covariant nor contravariant. A typical example is a reference:
```ocaml
# let x: x ref = ref \`X;;
val x : x ref = {contents = \`X}
```
If we were able to coerce x to the type xy ref as a variable xy, we could use xy to store the value \`Y inside the reference and then use the x value to read this content as a value of type x, which would break the type system.
More generally, as soon as a type variable appears in a position describing mutable state it becomes invariant. As a corollary, covariant variables will never denote mutable locations and can be safely generalized. For a better description, interested readers can consult the original article by Jacques Garrigue on [http://www.math.nagoya-u.ac.jp/\~garrigue/papers/morepoly-long.pdf](http://www.math.nagoya-u.ac.jp/~garrigue/papers/morepoly-long.pdf)
Together, the relaxed value restriction and type parameter covariance help to avoid eta-expansion in many situations.
|
### 1.5 Abstract data types
Moreover, when the type definitions are exposed, the type checker is able to infer variance information on its own and one can benefit from the relaxed value restriction even unknowingly. However, this is not the case anymore when defining new abstract types. As an illustration, we can define a module type collection as:
```ocaml
# module type COLLECTION = sig type 'a t val empty: unit -> 'a t end module Implementation = struct type 'a t = 'a list let empty ()= \[\] end;;
```
module type COLLECTION = sig type 'a t val empty : unit -> 'a t end module Implementation : sig type 'a t = 'a list val empty : unit -> 'a list end
```ocaml
# module List2: COLLECTION = Implementation;;
```
module List2 : COLLECTION
In this situation, when coercing the module List2 to the module type COLLECTION, the type checker forgets that 'a List2.t was covariant in 'a. Consequently, the relaxed value restriction does not apply anymore:
```ocaml
# List2.empty ();;
- : '\_weak5 List2.t = \<abstr>
```
To keep the relaxed value restriction, we need to declare the abstract type 'a COLLECTION.t as covariant in 'a:
```ocaml
# module type COLLECTION = sig type +'a t val empty: unit -> 'a t end module List2: COLLECTION = Implementation;;
```
module type COLLECTION = sig type +'a t val empty : unit -> 'a t end module List2 : COLLECTION
We then recover polymorphism:
```ocaml
# List2.empty ();;
- : 'a List2.t = \<abstr>
```
|
## 2 Polymorphic recursion
The second major class of non-genericity is directly related to the problem of type inference for polymorphic functions. In some circumstances, the type inferred by OCaml might be not general enough to allow the definition of some recursive functions, in particular for recursive functions acting on non-regular algebraic data types.
With a regular polymorphic algebraic data type, the type parameters of the type constructor are constant within the definition of the type. For instance, we can look at arbitrarily nested list defined as:
```ocaml
# type 'a regular_nested = List of 'a list \| Nested of 'a regular_nested list let l = Nested\[ List \[1\]; Nested \[List\[2;3\]\]; Nested\[Nested\[\]\] \];;
type 'a regular_nested = List of 'a list \| Nested of 'a regular_nested list val l : int regular_nested = Nested \[List \[1\]; Nested \[List \[2; 3\]\]; Nested \[Nested \[\]\]\]
```
Note that the type constructor regular_nested always appears as 'a regular_nested in the definition above, with the same parameter 'a. Equipped with this type, one can compute a maximal depth with a classic recursive function
```ocaml
# let rec maximal_depth = function \| List \_ -> 1 \| Nested \[\] -> 0 \| Nested (a::q) -> 1 + max (maximal_depth a) (maximal_depth (Nested q));;
val maximal_depth : 'a regular_nested -> int = \<fun\>
```
|
## 2 Polymorphic recursion
Non-regular recursive algebraic data types correspond to polymorphic algebraic data types whose parameter types vary between the left and right side of the type definition. For instance, it might be interesting to define a datatype that ensures that all lists are nested at the same depth:
```ocaml
# type 'a nested = List of 'a list \| Nested of 'a list nested;;
type 'a nested = List of 'a list \| Nested of 'a list nested
```
Intuitively, a value of type 'a nested is a list of list …of list of elements a with k nested list. We can then adapt the maximal_depth function defined on regular_depth into a depth function that computes this k. As a first try, we may define
```ocaml
# let rec depth = function \| List \_ -> 1 \| Nested n -> 1 + depth n;;
Error: This expression has type 'a list nested but an expression was expected of type 'a nested The type variable 'a occurs inside 'a list
```
|
## 2 Polymorphic recursion
The type error here comes from the fact that during the definition of depth, the type checker first assigns to depth the type 'a -> 'b . When typing the pattern matching, 'a -> 'b becomes 'a nested -> 'b, then 'a nested -> int once the List branch is typed. However, when typing the application depth n in the Nested branch, the type checker encounters a problem: depth n is applied to 'a list nested, it must therefore have the type 'a list nested -> 'b. Unifying this constraint with the previous one leads to the impossible constraint 'a list nested = 'a nested. In other words, within its definition, the recursive function depth is applied to values of type 'a t with different types 'a due to the non-regularity of the type constructor nested. This creates a problem because the type checker had introduced a new type variable 'a only at the *definition* of the function depth whereas, here, we need a different type variable for every *application* of the function depth.
|
### 2.1 Explicitly polymorphic annotations
The solution of this conundrum is to use an explicitly polymorphic type annotation for the type 'a:
```ocaml
# let rec depth: 'a. 'a nested -> int = function \| List \_ -> 1 \| Nested n -> 1 + depth n;;
val depth : 'a nested -> int = \<fun\>
# depth ( Nested(List \[ \[7\]; \[8\] \]) );;
- : int = 2
```
In the type of depth, 'a.'a nested -> int, the type variable 'a is universally quantified. In other words, 'a.'a nested -> int reads as “for all type 'a, depth maps 'a nested values to integers”. Whereas the standard type 'a nested -> int can be interpreted as “let be a type variable 'a, then depth maps 'a nested values to integers”. There are two major differences with these two type expressions. First, the explicit polymorphic annotation indicates to the type checker that it needs to introduce a new type variable every time the function depth is applied. This solves our problem with the definition of the function depth.
Second, it also notifies the type checker that the type of the function should be polymorphic. Indeed, without explicit polymorphic type annotation, the following type annotation is perfectly valid
```ocaml
# let sum: 'a -> 'b -> 'c = fun x y -> x + y;;
val sum : int -> int -> int = \<fun\>
```
since 'a,'b and 'c denote type variables that may or may not be polymorphic. Whereas, it is an error to unify an explicitly polymorphic type with a non-polymorphic type:
|
### 2.1 Explicitly polymorphic annotations
```ocaml
# let sum: 'a 'b 'c. 'a -> 'b -> 'c = fun x y -> x + y;;
Error: This definition has type int -> int -> int which is less general than 'a 'b 'c. 'a -> 'b -> 'c
```
An important remark here is that it is not needed to explicit fully the type of depth: it is sufficient to add annotations only for the universally quantified type variables:
```ocaml
# let rec depth: 'a. 'a nested -> \_ = function \| List \_ -> 1 \| Nested n -> 1 + depth n;;
val depth : 'a nested -> int = \<fun\>
# depth ( Nested(List \[ \[7\]; \[8\] \]) );;
- : int = 2
```
|
### 2.2 More examples
With explicit polymorphic annotations, it becomes possible to implement any recursive function that depends only on the structure of the nested lists and not on the type of the elements. For instance, a more complex example would be to compute the total number of elements of the nested lists:
```ocaml
# let len nested = let map_and_sum f = List.fold_left (fun acc x -> acc + f x) 0 in let rec len: 'a. ('a list -> int ) -> 'a nested -> int = fun nested_len n -> match n with \| List l -> nested_len l \| Nested n -> len (map_and_sum nested_len) n in len List.length nested;;
val len : 'a nested -> int = \<fun\>
# len (Nested(Nested(List \[ \[ \[1;2\]; \[3\] \]; \[ \[\]; \[4\]; \[5;6;7\]\]; \[\[\]\] \])));;
- : int = 7
```
Similarly, it may be necessary to use more than one explicitly polymorphic type variables, like for computing the nested list of list lengths of the nested list:
|
### 2.2 More examples
```ocaml
# let shape n = let rec shape: 'a 'b. ('a nested -> int nested) -> ('b list list -> 'a list) -> 'b nested -> int nested = fun nest nested_shape -> function \| List l -> raise (Invalid_argument "shape requires nested_list of depth greater than 1") \| Nested (List l) -> nest @@ List (nested_shape l) \| Nested n -> let nested_shape = List.map nested_shape in let nest x = nest (Nested x) in shape nest nested_shape n in shape (fun n -> n ) (fun l -> List.map List.length l ) n;;
val shape : 'a nested -> int nested = \<fun\>
# shape (Nested(Nested(List \[ \[ \[1;2\]; \[3\] \]; \[ \[\]; \[4\]; \[5;6;7\]\]; \[\[\]\] \])));;
- : int nested = Nested (List \[\[2; 1\]; \[0; 1; 3\]; \[0\]\])
```
|
## 3 Higher-rank polymorphic functions
Explicit polymorphic annotations are however not sufficient to cover all the cases where the inferred type of a function is less general than expected. A similar problem arises when using polymorphic functions as arguments of higher-order functions. For instance, we may want to compute the average depth or length of two nested lists:
```ocaml
# let average_depth x y = (depth x + depth y) / 2;;
val average_depth : 'a nested -> 'b nested -> int = \<fun\>
# let average_len x y = (len x + len y) / 2;;
val average_len : 'a nested -> 'b nested -> int = \<fun\>
# let one = average_len (List \[2\]) (List \[\[\]\]);;
val one : int = 1
```
It would be natural to factorize these two definitions as:
```ocaml
# let average f x y = (f x + f y) / 2;;
val average : ('a -> int) -> 'a -> 'a -> int = \<fun\>
```
However, the type of average len is less generic than the type of average_len, since it requires the type of the first and second argument to be the same:
```ocaml
# average_len (List \[2\]) (List \[\[\]\]);;
- : int = 1
# average len (List \[2\]) (List \[\[\]\]);;
Error: This expression has type 'a list but an expression was expected of type int
```
As previously with polymorphic recursion, the problem stems from the fact that type variables are introduced only at the start of the let definitions. When we compute both f x and f y, the type of x and y are unified together. To avoid this unification, we need to indicate to the type checker that f is polymorphic in its first argument. In some sense, we would want average to have type
|
## 3 Higher-rank polymorphic functions
val average: ('a. 'a nested -> int) -> 'a nested -> 'b nested -> int
Note that this syntax is not valid within OCaml: average has an universally quantified type 'a inside the type of one of its argument whereas for polymorphic recursion the universally quantified type was introduced before the rest of the type. This position of the universally quantified type means that average is a second-rank polymorphic function. This kind of higher-rank functions is not directly supported by OCaml: type inference for second-rank polymorphic function and beyond is undecidable; therefore using this kind of higher-rank functions requires to handle manually these universally quantified types.
In OCaml, there are two ways to introduce this kind of explicit universally quantified types: universally quantified record fields,
```ocaml
# type 'a nested_reduction = { f:'elt. 'elt nested -> 'a };;
type 'a nested_reduction = { f : 'elt. 'elt nested -> 'a; }
# let boxed_len = { f = len };;
val boxed_len : int nested_reduction = {f = \<fun\>}
```
and universally quantified object methods:
```ocaml
# let obj_len = object method f:'a. 'a nested -> 'b = len end;;
val obj_len : \< f : 'a. 'a nested -> int \> = \<obj>
```
To solve our problem, we can therefore use either the record solution:
```ocaml
# let average nsm x y = (nsm.f x + nsm.f y) / 2 ;;
val average : int nested_reduction -> 'a nested -> 'b nested -> int = \<fun\>
```
or the object one:
|
## 3 Higher-rank polymorphic functions
```ocaml
# let average (obj:\<f:'a. 'a nested -> \_ \> ) x y = (obj#f x + obj#f y) / 2 ;;
val average : \< f : 'a. 'a nested -> int \> -> 'b nested -> 'c nested -> int = \<fun\>
```
------------------------------------------------------------------------
[« Polymorphic variants](polyvariant.html)[Generalized algebraic datatypes »](gadts-tutorial.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Generalized algebraic datatypes
Source: https://ocaml.org/manual/5.2/gadts-tutorial.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 7 Generalized algebraic datatypes
Generalized algebraic datatypes, or GADTs, extend usual sum types in two ways: constraints on type parameters may change depending on the value constructor, and some type variables may be existentially quantified. Adding constraints is done by giving an explicit return type, where type parameters are instantiated:
type \_ term = \| Int : int -> int term \| Add : (int -> int -> int) term \| App : ('b -> 'a) term \* 'b term -> 'a term
This return type must use the same type constructor as the type being defined, and have the same number of parameters. Variables are made existential when they appear inside a constructor’s argument, but not in its return type. Since the use of a return type often eliminates the need to name type parameters in the left-hand side of a type definition, one can replace them with anonymous types \_ in that case.
The constraints associated to each constructor can be recovered through pattern-matching. Namely, if the type of the scrutinee of a pattern-matching contains a locally abstract type, this type can be refined according to the constructor used. These extra constraints are only valid inside the corresponding branch of the pattern-matching. If a constructor has some existential variables, fresh locally abstract types are generated, and they must not escape the scope of this branch.
|
## 1 Recursive functions
We write an eval function:
let rec eval : type a. a term -> a = function \| Int n -> n (\* a = int \*) \| Add -> (fun x y -> x+y) (\* a = int -> int -> int \*) \| App(f,x) -> (eval f) (eval x) (\* eval called at types (b->a) and b for fresh b \*)
And use it:
let two = eval (App (App (Add, Int 1), Int 1))
val two : int = 2
It is important to remark that the function eval is using the polymorphic syntax for locally abstract types. When defining a recursive function that manipulates a GADT, explicit polymorphic recursion should generally be used. For instance, the following definition fails with a type error:
let rec eval (type a) : a term -> a = function \| Int n -> n \| Add -> (fun x y -> x+y) \| App(f,x) -> (eval f) (eval x)
Error: This expression has type ($b -> a) term but an expression was expected of type 'a The type constructor $b would escape its scope Hint: $b is an existential type bound by the constructor App.
|
## 1 Recursive functions
In absence of an explicit polymorphic annotation, a monomorphic type is inferred for the recursive function. If a recursive call occurs inside the function definition at a type that involves an existential GADT type variable, this variable flows to the type of the recursive function, and thus escapes its scope. In the above example, this happens in the branch App(f,x) when eval is called with f as an argument. In this branch, the type of f is ($App\_'b -> a) term. The prefix $ in $App\_'b denotes an existential type named by the compiler (see [7.5](#s%3Aexistential-names)). Since the type of eval is 'a term -> 'a, the call eval f makes the existential type $App\_'b flow to the type variable 'a and escape its scope. This triggers the above error.
|
## 2 Type inference
Type inference for GADTs is notoriously hard. This is due to the fact some types may become ambiguous when escaping from a branch. For instance, in the Int case above, n could have either type int or a, and they are not equivalent outside of that branch. As a first approximation, type inference will always work if a pattern-matching is annotated with types containing no free type variables (both on the scrutinee and the return type). This is the case in the above example, thanks to the type annotation containing only locally abstract types.
In practice, type inference is a bit more clever than that: type annotations do not need to be immediately on the pattern-matching, and the types do not have to be always closed. As a result, it is usually enough to only annotate functions, as in the example above. Type annotations are propagated in two ways: for the scrutinee, they follow the flow of type inference, in a way similar to polymorphic methods; for the return type, they follow the structure of the program, they are split on functions, propagated to all branches of a pattern matching, and go through tuples, records, and sum types. Moreover, the notion of ambiguity used is stronger: a type is only seen as ambiguous if it was mixed with incompatible types (equated by constraints), without type annotations between them. For instance, the following program types correctly.
let rec sum : type a. a term -> \_ = fun x -> let y = match x with \| Int n -> n \| Add -> 0 \| App(f,x) -> sum f + sum x in y + 1
val sum : 'a term -> int = \<fun\>
|
## 2 Type inference
Here the return type int is never mixed with a, so it is seen as non-ambiguous, and can be inferred. When using such partial type annotations we strongly suggest specifying the -principal mode, to check that inference is principal.
The exhaustiveness check is aware of GADT constraints, and can automatically infer that some cases cannot happen. For instance, the following pattern matching is correctly seen as exhaustive (the Add case cannot happen).
let get_int : int term -> int = function \| Int n -> n \| App(\_,\_) -> 0
|
## 3 Refutation cases
Usually, the exhaustiveness check only tries to check whether the cases omitted from the pattern matching are typable or not. However, you can force it to try harder by adding *refutation cases*, written as a full stop. In the presence of a refutation case, the exhaustiveness check will first compute the intersection of the pattern with the complement of the cases preceding it. It then checks whether the resulting patterns can really match any concrete values by trying to type-check them. Wild cards in the generated patterns are handled in a special way: if their type is a variant type with only GADT constructors, then the pattern is split into the different constructors, in order to check whether any of them is possible (this splitting is not done for arguments of these constructors, to avoid non-termination). We also split tuples and variant types with only one case, since they may contain GADTs inside. For instance, the following code is deemed exhaustive:
type \_ t = \| Int : int t \| Bool : bool t let deep : (char t \* int) option -> char = function \| None -> 'c' \| \_ -> .
Namely, the inferred remaining case is Some \_, which is split into Some (Int, \_) and Some (Bool, \_), which are both untypable because deep expects a non-existing char t as the first element of the tuple. Note that the refutation case could be omitted here, because it is automatically added when there is only one case in the pattern matching.
|
## 3 Refutation cases
Another addition is that the redundancy check is now aware of GADTs: a case will be detected as redundant if it could be replaced by a refutation case using the same pattern.
|
## 4 Advanced examples
The term type we have defined above is an *indexed* type, where a type parameter reflects a property of the value contents. Another use of GADTs is *singleton* types, where a GADT value represents exactly one type. This value can be used as runtime representation for this type, and a function receiving it can have a polytypic behavior.
Here is an example of a polymorphic function that takes the runtime representation of some type t and a value of the same type, then pretty-prints the value as a string:
type \_ typ = \| Int : int typ \| String : string typ \| Pair : 'a typ \* 'b typ -> ('a \* 'b) typ let rec to_string: type t. t typ -> t -> string = fun t x -> match t with \| Int -> Int.to_string x \| String -> Printf.sprintf "%S" x \| Pair(t1,t2) -> let (x1, x2) = x in Printf.sprintf "(%s,%s)" (to_string t1 x1) (to_string t2 x2)
Another frequent application of GADTs is equality witnesses.
type (\_,\_) eq = Eq : ('a,'a) eq let cast : type a b. (a,b) eq -> a -> b = fun Eq x -> x
Here type eq has only one constructor, and by matching on it one adds a local constraint allowing the conversion between a and b. By building such equality witnesses, one can make equal types which are syntactically different.
Here is an example using both singleton types and equality witnesses to implement dynamic types.
|
## 4 Advanced examples
let rec eq_type : type a b. a typ -> b typ -> (a,b) eq option = fun a b -> match a, b with \| Int, Int -> Some Eq \| String, String -> Some Eq \| Pair(a1,a2), Pair(b1,b2) -> begin match eq_type a1 b1, eq_type a2 b2 with \| Some Eq, Some Eq -> Some Eq \| \_ -> None end \| \_ -> None type dyn = Dyn : 'a typ \* 'a -> dyn let get_dyn : type a. a typ -> dyn -> a option = fun a (Dyn(b,x)) -> match eq_type a b with \| None -> None \| Some Eq -> Some x
|
## 5 Existential type names in error messages
The typing of pattern matching in the presence of GADTs can generate many existential types. When necessary, error messages refer to these existential types using compiler-generated names. Currently, the compiler generates these names according to the following nomenclature:
- First, types whose name starts with a $ are existentials.
- $a denotes an existential type introduced for the type variable 'a of a GADT constructor:
type any = Any : 'name -> any let escape (Any x) = x
Error: This expression has type $name but an expression was expected of type 'a The type constructor $name would escape its scope Hint: $name is an existential type bound by the constructor Any.
- $'a if the existential variable was unified with the type variable 'a during typing:
type ('arg,'result,'aux) fn = \| Fun: ('a ->'b) -> ('a,'b,unit) fn \| Mem1: ('a ->'b) \* 'a \* 'b -> ('a, 'b, 'a \* 'b) fn let apply: ('arg,'result, \_ ) fn -> 'arg -> 'result = fun f x -> match f with \| Fun f -> f x \| Mem1 (f,y,fy) -> if x = y then fy else f x
Error: This pattern matches values of type ($'arg, 'result, $'arg \* 'result) fn but a pattern was expected which matches values of type ($'arg, 'result, unit) fn The type constructor $'arg would escape its scope
- $n (n a number) is an internally generated existential which could not be named using one of the previous schemes.
As shown by the last item, the current behavior is imperfect and may be improved in future versions.
|
## 6 Explicit naming of existentials
As explained above, pattern-matching on a GADT constructor may introduce existential types. Syntax has been introduced which allows them to be named explicitly. For instance, the following code names the type of the argument of f and uses this name.
type \_ closure = Closure : ('a -> 'b) \* 'a -> 'b closure let eval = fun (Closure (type a) (f, x : (a -> \_) \* \_)) -> f (x : a)
All existential type variables of the constructor must by introduced by the (type ...) construct and bound by a type annotation on the outside of the constructor argument.
|
## 7 Equations on non-local abstract types
GADT pattern-matching may also add type equations to non-local abstract types. The behaviour is the same as with local abstract types. Reusing the above eq type, one can write:
module M : sig type t val x : t val e : (t,int) eq end = struct type t = int let x = 33 let e = Eq end let x : int = let Eq = M.e in M.x
Of course, not all abstract types can be refined, as this would contradict the exhaustiveness check. Namely, builtin types (those defined by the compiler itself, such as int or array), and abstract types defined by the local module, are non-instantiable, and as such cause a type error rather than introduce an equation.
------------------------------------------------------------------------
[« Polymorphism and its limitations](polymorphism.html)[Advanced examples with classes and modules »](advexamples.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Advanced examples with classes and modules
Source: https://ocaml.org/manual/5.2/advexamples.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 8 Advanced examples with classes and modules
In this chapter, we show some larger examples using objects, classes and modules. We review many of the object features simultaneously on the example of a bank account. We show how modules taken from the standard library can be expressed as classes. Lastly, we describe a programming pattern known as *virtual types* through the example of window managers.
|
## 1 Extended example: bank accounts
In this section, we illustrate most aspects of Object and inheritance by refining, debugging, and specializing the following initial naive definition of a simple bank account. (We reuse the module Euro defined at the end of chapter [3](objectexamples.html#c%3Aobjectexamples).)
```ocaml
# let euro = new Euro.c;;
val euro : float -> Euro.c = \<fun\>
# let zero = euro 0.;;
val zero : Euro.c = \<obj>
# let neg x = x#times (-1.);;
val neg : \< times : float -> 'a; .. \> -> 'a = \<fun\>
# class account = object val mutable balance = zero method balance = balance method deposit x = balance \<- balance # plus x method withdraw x = if x#leq balance then (balance \<- balance # plus (neg x); x) else zero end;;
```
class account : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method withdraw : Euro.c -> Euro.c end
```ocaml
# let c = new account in c # deposit (euro 100.); c # withdraw (euro 50.);;
- : Euro.c = \<obj>
```
We now refine this definition with a method to compute interest.
```ocaml
# class account_with_interests = object (self) inherit account method private interest = self # deposit (self # balance # times 0.03) end;;
```
class account_with_interests : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method private interest : unit method withdraw : Euro.c -> Euro.c end
|
## 1 Extended example: bank accounts
We make the method interest private, since clearly it should not be called freely from the outside. Here, it is only made accessible to subclasses that will manage monthly or yearly updates of the account.
We should soon fix a bug in the current definition: the deposit method can be used for withdrawing money by depositing negative amounts. We can fix this directly:
```ocaml
# class safe_account = object inherit account method deposit x = if zero#leq x then balance \<- balance#plus x end;;
```
class safe_account : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method withdraw : Euro.c -> Euro.c end
However, the bug might be fixed more safely by the following definition:
```ocaml
# class safe_account = object inherit account as unsafe method deposit x = if zero#leq x then unsafe # deposit x else raise (Invalid_argument "deposit") end;;
```
class safe_account : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method withdraw : Euro.c -> Euro.c end
In particular, this does not require the knowledge of the implementation of the method deposit.
To keep track of operations, we extend the class with a mutable field history and a private method trace to add an operation in the log. Then each method to be traced is redefined.
|
## 1 Extended example: bank accounts
```ocaml
# type 'a operation = Deposit of 'a \| Retrieval of 'a;;
type 'a operation = Deposit of 'a \| Retrieval of 'a
# class account_with_history = object (self) inherit safe_account as super val mutable history = \[\] method private trace x = history \<- x :: history method deposit x = self#trace (Deposit x); super#deposit x method withdraw x = self#trace (Retrieval x); super#withdraw x method history = List.rev history end;;
```
class account_with_history : object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Euro.c -> Euro.c end
One may wish to open an account and simultaneously deposit some initial amount. Although the initial implementation did not address this requirement, it can be achieved by using an initializer.
```ocaml
# class account_with_deposit x = object inherit account_with_history initializer balance \<- x end;;
```
class account_with_deposit : Euro.c -> object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Euro.c -> Euro.c end
A better alternative is:
```ocaml
# class account_with_deposit x = object (self) inherit account_with_history initializer self#deposit x end;;
```
|
## 1 Extended example: bank accounts
class account_with_deposit : Euro.c -> object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Euro.c -> Euro.c end
Indeed, the latter is safer since the call to deposit will automatically benefit from safety checks and from the trace. Let’s test it:
```ocaml
# let ccp = new account_with_deposit (euro 100.) in let \_balance = ccp#withdraw (euro 50.) in ccp#history;;
- : Euro.c operation list = \[Deposit \<obj>; Retrieval \<obj>\]
```
Closing an account can be done with the following polymorphic function:
```ocaml
# let close c = c#withdraw c#balance;;
val close : \< balance : 'a; withdraw : 'a -> 'b; .. \> -> 'b = \<fun\>
```
Of course, this applies to all sorts of accounts.
Finally, we gather several versions of the account into a module Account abstracted over some currency.
|
## 1 Extended example: bank accounts
```ocaml
# let today () = (01,01,2000) (\* an approximation \*) module Account (M:MONEY) = struct type m = M.c let m = new M.c let zero = m 0. class bank = object (self) val mutable balance = zero method balance = balance val mutable history = \[\] method private trace x = history \<- x::history method deposit x = self#trace (Deposit x); if zero#leq x then balance \<- balance # plus x else raise (Invalid_argument "deposit") method withdraw x = if x#leq balance then (balance \<- balance # plus (neg x); self#trace (Retrieval x); x) else zero method history = List.rev history end class type client_view = object method deposit : m -> unit method history : m operation list method withdraw : m -> m method balance : m end class virtual check_client x = let y = if (m 100.)#leq x then x else raise (Failure "Insufficient initial deposit") in object (self) initializer self#deposit y method virtual deposit: m -> unit end module Client (B : sig class bank : client_view end) = struct class account x : client_view = object inherit B.bank inherit check_client x end let discount x = let c = new account x in if today() \< (1998,10,30) then c # deposit (m 100.); c end end;;
```
This shows the use of modules to group several class definitions that can in fact be thought of as a single unit. This unit would be provided by a bank for both internal and external uses. This is implemented as a functor that abstracts over the currency so that the same code can be used to provide accounts in different currencies.
|
## 1 Extended example: bank accounts
The class bank is the *real* implementation of the bank account (it could have been inlined). This is the one that will be used for further extensions, refinements, etc. Conversely, the client will only be given the client view.
```ocaml
# module Euro_account = Account(Euro);;
# module Client = Euro_account.Client (Euro_account);;
# new Client.account (new Euro.c 100.);;
```
Hence, the clients do not have direct access to the balance, nor the history of their own accounts. Their only way to change their balance is to deposit or withdraw money. It is important to give the clients a class and not just the ability to create accounts (such as the promotional discount account), so that they can personalize their account. For instance, a client may refine the deposit and withdraw methods so as to do his own financial bookkeeping, automatically. On the other hand, the function discount is given as such, with no possibility for further personalization.
It is important to provide the client’s view as a functor Client so that client accounts can still be built after a possible specialization of the bank. The functor Client may remain unchanged and be passed the new definition to initialize a client’s view of the extended account.
```ocaml
# module Investment_account (M : MONEY) = struct type m = M.c module A = Account(M) class bank = object inherit A.bank as super method deposit x = if (new M.c 1000.)#leq x then print_string "Would you like to invest?"; super#deposit x end module Client = A.Client end;;
```
|
## 1 Extended example: bank accounts
The functor Client may also be redefined when some new features of the account can be given to the client.
```ocaml
# module Internet_account (M : MONEY) = struct type m = M.c module A = Account(M) class bank = object inherit A.bank method mail s = print_string s end class type client_view = object method deposit : m -> unit method history : m operation list method withdraw : m -> m method balance : m method mail : string -> unit end module Client (B : sig class bank : client_view end) = struct class account x : client_view = object inherit B.bank inherit A.check_client x end end end;;
```
|
## 2 Simple modules as classes
One may wonder whether it is possible to treat primitive types such as integers and strings as objects. Although this is usually uninteresting for integers or strings, there may be some situations where this is desirable. The class money above is such an example. We show here how to do it for strings.
|
### 2.1 Strings
A naive definition of strings as objects could be:
```ocaml
# class ostring s = object method get n = String.get s n method print = print_string s method escaped = new ostring (String.escaped s) end;;
```
class ostring : string -> object method escaped : ostring method get : int -> char method print : unit end
However, the method escaped returns an object of the class ostring, and not an object of the current class. Hence, if the class is further extended, the method escaped will only return an object of the parent class.
```ocaml
# class sub_string s = object inherit ostring s method sub start len = new sub_string (String.sub s start len) end;;
```
class sub_string : string -> object method escaped : ostring method get : int -> char method print : unit method sub : int -> int -> sub_string end
As seen in section [3.16](objectexamples.html#s%3Abinary-methods), the solution is to use functional update instead. We need to create an instance variable containing the representation s of the string.
```ocaml
# class better_string s = object val repr = s method get n = String.get repr n method print = print_string repr method escaped = {\< repr = String.escaped repr \>} method sub start len = {\< repr = String.sub s start len \>} end;;
```
class better_string : string -> object ('a) val repr : string method escaped : 'a method get : int -> char method print : unit method sub : int -> int -> 'a end
As shown in the inferred type, the methods escaped and sub now return objects of the same type as the one of the class.
|
### 2.1 Strings
Another difficulty is the implementation of the method concat. In order to concatenate a string with another string of the same class, one must be able to access the instance variable externally. Thus, a method repr returning s must be defined. Here is the correct definition of strings:
```ocaml
# class ostring s = object (self : 'mytype) val repr = s method repr = repr method get n = String.get repr n method print = print_string repr method escaped = {\< repr = String.escaped repr \>} method sub start len = {\< repr = String.sub s start len \>} method concat (t : 'mytype) = {\< repr = repr ^ t#repr \>} end;;
```
class ostring : string -> object ('a) val repr : string method concat : 'a -> 'a method escaped : 'a method get : int -> char method print : unit method repr : string method sub : int -> int -> 'a end
Another constructor of the class string can be defined to return a new string of a given length:
```ocaml
# class cstring n = ostring (String.make n ' ');;
```
class cstring : int -> ostring
Here, exposing the representation of strings is probably harmless. We do could also hide the representation of strings as we hid the currency in the class money of section [3.17](objectexamples.html#s%3Afriends).
|
#### Stacks
There is sometimes an alternative between using modules or classes for parametric data types. Indeed, there are situations when the two approaches are quite similar. For instance, a stack can be straightforwardly implemented as a class:
```ocaml
# exception Empty;;
```
exception Empty
```ocaml
# class \['a\] stack = object val mutable l = (\[\] : 'a list) method push x = l \<- x::l method pop = match l with \[\] -> raise Empty \| a::l' -> l \<- l'; a method clear = l \<- \[\] method length = List.length l end;;
```
class \['a\] stack : object val mutable l : 'a list method clear : unit method length : int method pop : 'a method push : 'a -> unit end
However, writing a method for iterating over a stack is more problematic. A method fold would have type ('b -> 'a -> 'b) -> 'b -> 'b. Here 'a is the parameter of the stack. The parameter 'b is not related to the class 'a stack but to the argument that will be passed to the method fold. A naive approach is to make 'b an extra parameter of class stack:
```ocaml
# class \['a, 'b\] stack2 = object inherit \['a\] stack method fold f (x : 'b) = List.fold_left f x l end;;
```
class \['a, 'b\] stack2 : object val mutable l : 'a list method clear : unit method fold : ('b -> 'a -> 'b) -> 'b -> 'b method length : int method pop : 'a method push : 'a -> unit end
However, the method fold of a given object can only be applied to functions that all have the same type:
```ocaml
# let s = new stack2;;
val s : ('\_weak1, '\_weak2) stack2 = \<obj>
# s#fold ( + ) 0;;
- : int = 0
# s;;
- : (int, int) stack2 = \<obj>
```
|
### 2.1 Strings
A better solution is to use polymorphic methods, which were introduced in OCaml version 3.05. Polymorphic methods makes it possible to treat the type variable 'b in the type of fold as universally quantified, giving fold the polymorphic type Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b. An explicit type declaration on the method fold is required, since the type checker cannot infer the polymorphic type by itself.
```ocaml
# class \['a\] stack3 = object inherit \['a\] stack method fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b = fun f x -> List.fold_left f x l end;;
```
class \['a\] stack3 : object val mutable l : 'a list method clear : unit method fold : ('b -> 'a -> 'b) -> 'b -> 'b method length : int method pop : 'a method push : 'a -> unit end
|
### 2.2 Hashtbl
A simplified version of object-oriented hash tables should have the following class type.
```ocaml
# class type \['a, 'b\] hash_table = object method find : 'a -> 'b method add : 'a -> 'b -> unit end;;
```
class type \['a, 'b\] hash_table = object method add : 'a -> 'b -> unit method find : 'a -> 'b end
A simple implementation, which is quite reasonable for small hash tables is to use an association list:
```ocaml
# class \['a, 'b\] small_hashtbl : \['a, 'b\] hash_table = object val mutable table = \[\] method find key = List.assoc key table method add key value = table \<- (key, value) :: table end;;
```
class \['a, 'b\] small_hashtbl : \['a, 'b\] hash_table
A better implementation, and one that scales up better, is to use a true hash table… whose elements are small hash tables!
```ocaml
# class \['a, 'b\] hashtbl size : \['a, 'b\] hash_table = object (self) val table = Array.init size (fun i -> new small_hashtbl) method private hash key = (Hashtbl.hash key) mod (Array.length table) method find key = table.(self#hash key) # find key method add key = table.(self#hash key) # add key end;;
```
class \['a, 'b\] hashtbl : int -> \['a, 'b\] hash_table
|
### 2.3 Sets
Implementing sets leads to another difficulty. Indeed, the method union needs to be able to access the internal representation of another object of the same class.
This is another instance of friend functions as seen in section [3.17](objectexamples.html#s%3Afriends). Indeed, this is the same mechanism used in the module Set in the absence of objects.
In the object-oriented version of sets, we only need to add an additional method tag to return the representation of a set. Since sets are parametric in the type of elements, the method tag has a parametric type 'a tag, concrete within the module definition but abstract in its signature. From outside, it will then be guaranteed that two objects with a method tag of the same type will share the same representation.
```ocaml
# module type SET = sig type 'a tag class \['a\] c : object ('b) method is_empty : bool method mem : 'a -> bool method add : 'a -> 'b method union : 'b -> 'b method iter : ('a -> unit) -> unit method tag : 'a tag end end;;
# module Set : SET = struct let rec merge l1 l2 = match l1 with \[\] -> l2 \| h1 :: t1 -> match l2 with \[\] -> l1 \| h2 :: t2 -> if h1 \< h2 then h1 :: merge t1 l2 else if h1 \> h2 then h2 :: merge l1 t2 else merge t1 l2 type 'a tag = 'a list class \['a\] c = object (\_ : 'b) val repr = (\[\] : 'a list) method is_empty = (repr = \[\]) method mem x = List.exists (( = ) x) repr method add x = {\< repr = merge \[x\] repr \>} method union (s : 'b) = {\< repr = merge repr s#tag \>} method iter (f : 'a -> unit) = List.iter f repr method tag = repr end end;;
```
|
## 3 The subject/observer pattern
The following example, known as the subject/observer pattern, is often presented in the literature as a difficult inheritance problem with inter-connected classes. The general pattern amounts to the definition a pair of two classes that recursively interact with one another.
The class observer has a distinguished method notify that requires two arguments, a subject and an event to execute an action.
```ocaml
# class virtual \['subject, 'event\] observer = object method virtual notify : 'subject -> 'event -> unit end;;
```
class virtual \['subject, 'event\] observer : object method virtual notify : 'subject -> 'event -> unit end
The class subject remembers a list of observers in an instance variable, and has a distinguished method notify_observers to broadcast the message notify to all observers with a particular event e.
```ocaml
# class \['observer, 'event\] subject = object (self) val mutable observers = (\[\]:'observer list) method add_observer obs = observers \<- (obs :: observers) method notify_observers (e : 'event) = List.iter (fun x -> x#notify self e) observers end;;
```
class \['a, 'event\] subject : object ('b) constraint 'a = \< notify : 'b -> 'event -> unit; .. \> val mutable observers : 'a list method add_observer : 'a -> unit method notify_observers : 'event -> unit end
The difficulty usually lies in defining instances of the pattern above by inheritance. This can be done in a natural and obvious manner in OCaml, as shown on the following example manipulating windows.
|
## 3 The subject/observer pattern
```ocaml
# type event = Raise \| Resize \| Move;;
type event = Raise \| Resize \| Move
# let string_of_event = function Raise -> "Raise" \| Resize -> "Resize" \| Move -> "Move";;
val string_of_event : event -> string = \<fun\>
# let count = ref 0;;
val count : int ref = {contents = 0}
# class \['observer\] window_subject = let id = count := succ !count; !count in object (self) inherit \['observer, event\] subject val mutable position = 0 method identity = id method move x = position \<- position + x; self#notify_observers Move method draw = Printf.printf "{Position = %d}\\n" position; end;;
```
class \['a\] window_subject : object ('b) constraint 'a = \< notify : 'b -> event -> unit; .. \> val mutable observers : 'a list val mutable position : int method add_observer : 'a -> unit method draw : unit method identity : int method move : int -> unit method notify_observers : event -> unit end
```ocaml
# class \['subject\] window_observer = object inherit \['subject, event\] observer method notify s e = s#draw end;;
```
class \['a\] window_observer : object constraint 'a = \< draw : unit; .. \> method notify : 'a -> event -> unit end
As can be expected, the type of window is recursive.
```ocaml
# let window = new window_subject;;
val window : (\< notify : 'a -> event -> unit; .. \> as '\_weak3) window_subject as 'a = \<obj>
```
However, the two classes of window_subject and window_observer are not mutually recursive.
|
## 3 The subject/observer pattern
```ocaml
# let window_observer = new window_observer;;
val window_observer : (\< draw : unit; .. \> as '\_weak4) window_observer = \<obj>
# window#add_observer window_observer;;
- : unit = ()
# window#move 1;;
```
{Position = 1} - : unit = ()
Classes window_observer and window_subject can still be extended by inheritance. For instance, one may enrich the subject with new behaviors and refine the behavior of the observer.
```ocaml
# class \['observer\] richer_window_subject = object (self) inherit \['observer\] window_subject val mutable size = 1 method resize x = size \<- size + x; self#notify_observers Resize val mutable top = false method raise = top \<- true; self#notify_observers Raise method draw = Printf.printf "{Position = %d; Size = %d}\\n" position size; end;;
```
class \['a\] richer_window_subject : object ('b) constraint 'a = \< notify : 'b -> event -> unit; .. \> val mutable observers : 'a list val mutable position : int val mutable size : int val mutable top : bool method add_observer : 'a -> unit method draw : unit method identity : int method move : int -> unit method notify_observers : event -> unit method raise : unit method resize : int -> unit end
```ocaml
# class \['subject\] richer_window_observer = object inherit \['subject\] window_observer as super method notify s e = if e \<\> Raise then s#raise; super#notify s e end;;
```
class \['a\] richer_window_observer : object constraint 'a = \< draw : unit; raise : unit; .. \> method notify : 'a -> event -> unit end
We can also create a different kind of observer:
|
## 3 The subject/observer pattern
```ocaml
# class \['subject\] trace_observer = object inherit \['subject, event\] observer method notify s e = Printf.printf "\<Window %d \<== %s>\\n" s#identity (string_of_event e) end;;
```
class \['a\] trace_observer : object constraint 'a = \< identity : int; .. \> method notify : 'a -> event -> unit end
and attach several observers to the same object:
```ocaml
# let window = new richer_window_subject;;
val window : (\< notify : 'a -> event -> unit; .. \> as '\_weak5) richer_window_subject as 'a = \<obj>
# window#add_observer (new richer_window_observer);;
- : unit = ()
# window#add_observer (new trace_observer);;
- : unit = ()
# window#move 1; window#resize 2;;
```
\<Window 1 \<== Move> \<Window 1 \<== Raise> {Position = 1; Size = 1} {Position = 1; Size = 1} \<Window 1 \<== Resize> \<Window 1 \<== Raise> {Position = 1; Size = 3} {Position = 1; Size = 3} - : unit = ()
------------------------------------------------------------------------
[« Generalized algebraic datatypes](gadts-tutorial.html)[Parallel programming »](parallelism.html)
(Chapter written by Didier Rémy)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Parallel programming
Source: https://ocaml.org/manual/5.2/parallelism.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 9 Parallel programming
In this chapter, we shall look at the parallel programming facilities in OCaml. The OCaml standard library exposes low-level primitives for parallel programming. We recommend the users to utilise higher-level parallel programming libraries such as [domainslib](https://github.com/ocaml-multicore/domainslib). This tutorial will first cover the high-level parallel programming using domainslib followed by low-level primitives exposed by the compiler.
OCaml distinguishes concurrency and parallelism and provides distinct mechanisms for expressing them. Concurrency is overlapped execution of tasks (section [12.24.2](effects.html#s%3Aeffects-concurrency)) whereas parallelism is simultaneous execution of tasks. In particular, parallel tasks overlap in time but concurrent tasks may or may not overlap in time. Tasks may execute concurrently by yielding control to each other. While concurrency is a program structuring mechanism, parallelism is a mechanism to make your programs run faster. If you are interested in the concurrent programming mechanisms in OCaml, please refer to the section [12.24](effects.html#s%3Aeffect-handlers) on effect handlers and the chapter [34](libthreads.html#c%3Athreads) on the threads library.
|
## 1 Domains
Domains are the units of parallelism in OCaml. The module [Domain](../5.2/api/Domain.html) provides the primitives to create and manage domains. New domains can be spawned using the spawn function.
Domain.spawn (fun \_ -> print_endline "I ran in parallel")
I ran in parallel - : unit Domain.t = \<abstr>
The spawn function executes the given computation in parallel with the calling domain.
Domains are heavy-weight entities. Each domain maps 1:1 to an operating system thread. Each domain also has its own runtime state, which includes domain-local structures for allocating memory. Hence, they are relatively expensive to create and tear down.
*It is recommended that the programs do not spawn more domains than cores available*.
In this tutorial, we shall be implementing, running and measuring the performance of parallel programs. The results observed are dependent on the number of cores available on the target machine. This tutorial is being written on a 2.3 GHz Quad-Core Intel Core i7 MacBook Pro with 4 cores and 8 hardware threads. It is reasonable to expect roughly 4x performance on 4 domains for parallel programs with little coordination between the domains, and when the machine is not under load. Beyond 4 domains, the speedup is likely to be less than linear. We shall also use the command-line benchmarking tool [hyperfine](https://github.com/sharkdp/hyperfine) for benchmarking our programs.
|
### 1.1 Joining domains
We shall use the program to compute the nth Fibonacci number using recursion as a running example. The sequential program for computing the nth Fibonacci number is given below.
(\* fib.ml \*) let n = try int_of_string Sys.argv.(1) with \_ -> 1 let rec fib n = if n \< 2 then 1 else fib (n - 1) + fib (n - 2) let main () = let r = fib n in Printf.printf "fib(%d) = %d\\n%!" n r let \_ = main ()
The program can be compiled and benchmarked as follows.
$ ocamlopt -o fib.exe fib.ml
$ ./fib.exe 42
fib(42) = 433494437
$ hyperfine './fib.exe 42' # Benchmarking
Benchmark 1: ./fib.exe 42
Time (mean ± sd): 1.193 s ± 0.006 s [User: 1.186 s, System: 0.003 s]
Range (min … max): 1.181 s … 1.202 s 10 runs
We see that it takes around 1.2 seconds to compute the 42nd Fibonacci number.
Spawned domains can be joined using the join function to get their results. The join function waits for target domain to terminate. The following program computes the nth Fibonacci number twice in parallel.
(\* fib_twice.ml \*) let n = int_of_string Sys.argv.(1) let rec fib n = if n \< 2 then 1 else fib (n - 1) + fib (n - 2) let main () = let d1 = Domain.spawn (fun \_ -> fib n) in let d2 = Domain.spawn (fun \_ -> fib n) in let r1 = Domain.join d1 in Printf.printf "fib(%d) = %d\\n%!" n r1; let r2 = Domain.join d2 in Printf.printf "fib(%d) = %d\\n%!" n r2 let \_ = main ()
|
### 1.1 Joining domains
The program spawns two domains which compute the nth Fibonacci number. The spawn function returns a Domain.t value which can be joined to get the result of the parallel computation. The join function blocks until the computation runs to completion.
$ ocamlopt -o fib_twice.exe fib_twice.ml
$ ./fib_twice.exe 42
fib(42) = 433494437
fib(42) = 433494437
$ hyperfine './fib_twice.exe 42'
Benchmark 1: ./fib_twice.exe 42
Time (mean ± sd): 1.249 s ± 0.025 s [User: 2.451 s, System: 0.012 s]
Range (min … max): 1.221 s … 1.290 s 10 runs
As one can see that computing the nth Fibonacci number twice almost took the same time as computing it once thanks to parallelism.
|
## 2 Domainslib: A library for nested-parallel programming
Let us attempt to parallelise the Fibonacci function. The two recursive calls may be executed in parallel. However, naively parallelising the recursive calls by spawning domains for each one will not work as it spawns too many domains.
(\* fib_par1.ml \*) let n = try int_of_string Sys.argv.(1) with \_ -> 1 let rec fib n = if n \< 2 then 1 else begin let d1 = Domain.spawn (fun \_ -> fib (n - 1)) in let d2 = Domain.spawn (fun \_ -> fib (n - 2)) in Domain.join d1 + Domain.join d2 end let main () = let r = fib n in Printf.printf "fib(%d) = %d\\n%!" n r let \_ = main ()
fib(1) = 1 val n : int = 1 val fib : int -> int = \<fun\> val main : unit -> unit = \<fun\>
$ ocamlopt -o fib_par1.exe fib_par1.ml
$ ./fib_par1.exe 42
Fatal error: exception Failure("failed to allocate domain")
OCaml has a limit of 128 domains that can be active at the same time. An attempt to spawn more domains will raise an exception. How then can we parallelise the Fibonacci function?
|
### 2.1 Parallelising Fibonacci using domainslib
The OCaml standard library provides only low-level primitives for concurrent and parallel programming, leaving high-level programming libraries to be developed and distributed outside the core compiler distribution. [Domainslib](https://github.com/ocaml-multicore/domainslib) is such a library for nested-parallel programming, which is epitomised by the parallelism available in the recursive Fibonacci computation. Let us use domainslib to parallelise the recursive Fibonacci program. It is recommended that you install domainslib using the [opam](https://opam.ocaml.org/) package manager. This tutorial uses domainslib version 0.5.0.
Domainslib provides an async/await mechanism for spawning parallel tasks and awaiting their results. On top of this mechanism, domainslib provides parallel iterators. At its core, domainslib has an efficient implementation of work-stealing queue in order to efficiently share tasks with other domains. A parallel implementation of the Fibonacci program is given below.
(* fib_par2.ml *)
let num_domains = int_of_string Sys.argv.(1)
let n = int_of_string Sys.argv.(2)
let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)
module T = Domainslib.Task
let rec fib_par pool n =
if n > 20 then begin
let a = T.async pool (fun _ -> fib_par pool (n-1)) in
let b = T.async pool (fun _ -> fib_par pool (n-2)) in
T.await pool a + T.await pool b
end else fib n
|
### 2.1 Parallelising Fibonacci using domainslib
let main () =
let pool = T.setup_pool ~num_domains:(num_domains - 1) () in
let res = T.run pool (fun _ -> fib_par pool n) in
T.teardown_pool pool;
Printf.printf "fib(%d) = %d\n" n res
let _ = main ()
The program takes the number of domains and the input to the Fibonacci function as the first and the second command-line arguments respectively.
Let us start with the main function. First, we set up a pool of domains on which the nested parallel tasks will run. The domain invoking the run function will also participate in executing the tasks submitted to the pool. We invoke the parallel Fibonacci function fib_par in the run function. Finally, we tear down the pool and print the result.
For sufficiently large inputs (n \> 20), the fib_par function spawns the left and the right recursive calls asynchronously in the pool using the async function. The async function returns a promise for the result. The result of an asynchronous computation is obtained by awaiting the promise using the await function. The await function call blocks until the promise is resolved.
For small inputs, the fib_par function simply calls the sequential Fibonacci function fib. It is important to switch to sequential mode for small problem sizes. If not, the cost of parallelisation will outweigh the work available.
|
### 2.1 Parallelising Fibonacci using domainslib
For simplicity, we use ocamlfind to compile this program. It is recommended that the users use [dune](https://github.com/ocaml/dune) to build their programs that utilise libraries installed through [opam](https://opam.ocaml.org/).
$ ocamlfind ocamlopt -package domainslib -linkpkg -o fib_par2.exe fib_par2.ml
$ ./fib_par2.exe 1 42
fib(42) = 433494437
$ hyperfine './fib.exe 42' './fib_par2.exe 2 42' \
'./fib_par2.exe 4 42' './fib_par2.exe 8 42'
Benchmark 1: ./fib.exe 42
Time (mean ± sd): 1.217 s ± 0.018 s [User: 1.203 s, System: 0.004 s]
Range (min … max): 1.202 s … 1.261 s 10 runs
Benchmark 2: ./fib_par2.exe 2 42
Time (mean ± sd): 628.2 ms ± 2.9 ms [User: 1243.1 ms, System: 4.9 ms]
Range (min … max): 625.7 ms … 634.5 ms 10 runs
Benchmark 3: ./fib_par2.exe 4 42
Time (mean ± sd): 337.6 ms ± 23.4 ms [User: 1321.8 ms, System: 8.4 ms]
Range (min … max): 318.5 ms … 377.6 ms 10 runs
Benchmark 4: ./fib_par2.exe 8 42
Time (mean ± sd): 250.0 ms ± 9.4 ms [User: 1877.1 ms, System: 12.6 ms]
Range (min … max): 242.5 ms … 277.3 ms 11 runs
Summary
'./fib_par2.exe 8 42' ran
1.35 ± 0.11 times faster than './fib_par2.exe 4 42'
2.51 ± 0.10 times faster than './fib_par2.exe 2 42'
4.87 ± 0.20 times faster than './fib.exe 42'
The results show that, with 8 domains, the parallel Fibonacci program runs 4.87 times faster than the sequential version.
|
### 2.2 Parallel iteration constructs
Many numerical algorithms use for-loops. The parallel-for primitive provides a straight-forward way to parallelise such code. Let us take the [spectral-norm](https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/spectralnorm.html#spectralnorm) benchmark from the computer language benchmarks game and parallelise it. The sequential version of the program is given below.
(\* spectralnorm.ml \*) let n = try int_of_string Sys.argv.(1) with \_ -> 32 let eval_A i j = 1. /. float((i+j)\*(i+j+1)/2+i+1) let eval_A\_times_u u v = let n = Array.length v - 1 in for i = 0 to n do let vi = ref 0. in for j = 0 to n do vi := !vi +. eval_A i j \*. u.(j) done; v.(i) \<- !vi done let eval_At_times_u u v = let n = Array.length v - 1 in for i = 0 to n do let vi = ref 0. in for j = 0 to n do vi := !vi +. eval_A j i \*. u.(j) done; v.(i) \<- !vi done let eval_AtA_times_u u v = let w = Array.make (Array.length u) 0.0 in eval_A\_times_u u w; eval_At_times_u w v let () = let u = Array.make n 1.0 and v = Array.make n 0.0 in for \_i = 0 to 9 do eval_AtA_times_u u v; eval_AtA_times_u v u done; let vv = ref 0.0 and vBv = ref 0.0 in for i=0 to n-1 do vv := !vv +. v.(i) \*. v.(i); vBv := !vBv +. u.(i) \*. v.(i) done; Printf.printf "%0.9f\\n" (sqrt(!vBv /. !vv))
Observe that the program has nested loops in eval_A\_times_u and eval_At_times_u. Each iteration of the outer loop body reads from u but writes to disjoint memory locations in v. Hence, the iterations of the outer loop are not dependent on each other and can be executed in parallel.
|
### 2.2 Parallel iteration constructs
The parallel version of spectral norm is shown below.
(* spectralnorm_par.ml *)
let num_domains = try int_of_string Sys.argv.(1) with _ -> 1
let n = try int_of_string Sys.argv.(2) with _ -> 32
let eval_A i j = 1. /. float((i+j)*(i+j+1)/2+i+1)
module T = Domainslib.Task
let eval_A_times_u pool u v =
let n = Array.length v - 1 in
T.parallel_for pool ~start:0 ~finish:n ~body:(fun i ->
let vi = ref 0. in
for j = 0 to n do vi := !vi +. eval_A i j *. u.(j) done;
v.(i) <- !vi
)
let eval_At_times_u pool u v =
let n = Array.length v - 1 in
T.parallel_for pool ~start:0 ~finish:n ~body:(fun i ->
let vi = ref 0. in
for j = 0 to n do vi := !vi +. eval_A j i *. u.(j) done;
v.(i) <- !vi
)
let eval_AtA_times_u pool u v =
let w = Array.make (Array.length u) 0.0 in
eval_A_times_u pool u w; eval_At_times_u pool w v
let () =
let pool = T.setup_pool ~num_domains:(num_domains - 1) () in
let u = Array.make n 1.0 and v = Array.make n 0.0 in
T.run pool (fun _ ->
for _i = 0 to 9 do
eval_AtA_times_u pool u v; eval_AtA_times_u pool v u
done);
let vv = ref 0.0 and vBv = ref 0.0 in
for i=0 to n-1 do
vv := !vv +. v.(i) *. v.(i);
vBv := !vBv +. u.(i) *. v.(i)
done;
T.teardown_pool pool;
Printf.printf "%0.9f\n" (sqrt(!vBv /. !vv))
|
### 2.2 Parallel iteration constructs
Observe that the parallel_for function is isomorphic to the for-loop in the sequential version. No other change is required except for the boiler plate code to set up and tear down the pools.
$ ocamlopt -o spectralnorm.exe spectralnorm.ml
$ ocamlfind ocamlopt -package domainslib -linkpkg -o spectralnorm_par.exe \
spectralnorm_par.ml
$ hyperfine './spectralnorm.exe 4096' './spectralnorm_par.exe 2 4096' \
'./spectralnorm_par.exe 4 4096' './spectralnorm_par.exe 8 4096'
Benchmark 1: ./spectralnorm.exe 4096
Time (mean ± sd): 1.989 s ± 0.013 s [User: 1.972 s, System: 0.007 s]
Range (min … max): 1.975 s … 2.018 s 10 runs
Benchmark 2: ./spectralnorm_par.exe 2 4096
Time (mean ± sd): 1.083 s ± 0.015 s [User: 2.140 s, System: 0.009 s]
Range (min … max): 1.064 s … 1.102 s 10 runs
Benchmark 3: ./spectralnorm_par.exe 4 4096
Time (mean ± sd): 698.7 ms ± 10.3 ms [User: 2730.8 ms, System: 18.3 ms]
Range (min … max): 680.9 ms … 721.7 ms 10 runs
Benchmark 4: ./spectralnorm_par.exe 8 4096
Time (mean ± sd): 921.8 ms ± 52.1 ms [User: 6711.6 ms, System: 51.0 ms]
Range (min … max): 838.6 ms … 989.2 ms 10 runs
Summary
'./spectralnorm_par.exe 4 4096' ran
1.32 ± 0.08 times faster than './spectralnorm_par.exe 8 4096'
1.55 ± 0.03 times faster than './spectralnorm_par.exe 2 4096'
2.85 ± 0.05 times faster than './spectralnorm.exe 4096'
|
### 2.2 Parallel iteration constructs
On the author’s machine, the program scales reasonably well up to 4 domains but performs worse with 8 domains. Recall that the machine only has 4 physical cores. Debugging and fixing this performance issue is beyond the scope of this tutorial.
|
## 3 Parallel garbage collection
An important aspect of the scalability of parallel OCaml programs is the scalability of the garbage collector (GC). The OCaml GC is designed to have both low latency and good parallel scalability. OCaml has a generational garbage collector with a small minor heap and a large major heap. New objects (upto a certain size) are allocated in the minor heap. Each domain has its own domain-local minor heap arena into which new objects are allocated without synchronising with the other domains. When a domain exhausts its minor heap arena, it calls for a stop-the-world collection of the minor heaps. In the stop-the-world section, all the domains collect their minor heap arenas in parallel evacuating the survivors to the major heap.
For the major heap, each domain maintains domain-local, size-segmented pools of memory into which large objects and survivors from the minor collection are allocated. Having domain-local pools avoids synchronisation for most major heap allocations. The major heap is collected by a concurrent mark-and-sweep algorithm that involves a few short stop-the-world pauses for each major cycle.
Overall, the users should expect the garbage collector to scale well with increasing number of domains, with the latency remaining low. For more information on the design and evaluation of the garbage collector, please have a look at the ICFP 2020 paper on [Retrofitting Parallelism onto OCaml](https://arxiv.org/abs/2004.11663).
|
## 4 Memory model: The easy bits
Modern processors and compilers aggressively optimise programs. These optimisations accelerate without otherwise affecting sequential programs, but cause surprising behaviours to be visible in parallel programs. To benefit from these optimisations, OCaml adopts a relaxed memory model that precisely specifies which of these *relaxed behaviours* programs may observe. While these models are difficult to program against directly, the OCaml memory model provides recipes that retain the simplicity of sequential reasoning.
Firstly, immutable values may be freely shared between multiple domains and may be accessed in parallel. For mutable data structures such as reference cells, arrays and mutable record fields, programmers should avoid *data races*. Reference cells, arrays and mutable record fields are said to be *non-atomic* data structures. A data race is said to occur when two domains concurrently access a non-atomic memory location without *synchronisation* and at least one of the accesses is a write. OCaml provides a number of ways to introduce synchronisation including atomic variables (section [9.7](#s%3Apar_atomics)) and mutexes (section [9.5](#s%3Apar_sync)).
|
## 4 Memory model: The easy bits
Importantly, for data race free (DRF) programs, OCaml provides sequentially consistent (SC) semantics – the observed behaviour of such programs can be explained by the interleaving of operations from different domains. This property is known as DRF-SC guarantee. Moreover, in OCaml, DRF-SC guarantee is modular – if a part of a program is data race free, then the OCaml memory model ensures that those parts have sequential consistency despite other parts of the program having data races. Even for programs with data races, OCaml provides strong guarantees. While the user may observe non sequentially consistent behaviours, there are no crashes.
For more details on the relaxed behaviours in the presence of data races, please have a look at the chapter on the hard bits of the memory model (chapter [10](memorymodel.html#c%3Amemorymodel)).
|
## 5 Blocking synchronisation
Domains may perform blocking synchronisation with the help of [Mutex](../5.2/api/Mutex.html), [Condition](../5.2/api/Condition.html) and [Semaphore](../5.2/api/Semaphore.html) modules. These modules are the same as those used to synchronise threads created by the threads library (chapter [34](libthreads.html#c%3Athreads)). For clarity, in the rest of this chapter, we shall call the threads created by the threads library as *systhreads*. The following program implements a concurrent stack using mutex and condition variables.
module Blocking_stack : sig type 'a t val make : unit -> 'a t val push : 'a t -> 'a -> unit val pop : 'a t -> 'a end = struct type 'a t = { mutable contents: 'a list; mutex : Mutex.t; nonempty : Condition.t } let make () = { contents = \[\]; mutex = Mutex.create (); nonempty = Condition.create () } let push r v = Mutex.lock r.mutex; r.contents \<- v::r.contents; Condition.signal r.nonempty; Mutex.unlock r.mutex let pop r = Mutex.lock r.mutex; let rec loop () = match r.contents with \| \[\] -> Condition.wait r.nonempty r.mutex; loop () \| x::xs -> r.contents \<- xs; x in let res = loop () in Mutex.unlock r.mutex; res end
The concurrent stack is implemented using a record with three fields: a mutable field contents which stores the elements in the stack, a mutex to control access to the contents field, and a condition variable nonempty, which is used to signal blocked domains waiting for the stack to become non-empty.
|
## 5 Blocking synchronisation
The push operation locks the mutex, updates the contents field with a new list whose head is the element being pushed and the tail is the old list. The condition variable nonempty is signalled while the lock is held in order to wake up any domains waiting on this condition. If there are waiting domains, one of the domains is woken up. If there are none, then the signal operation has no effect.
The pop operation locks the mutex and checks whether the stack is empty. If so, the calling domain waits on the condition variable nonempty using the wait primitive. The wait call atomically suspends the execution of the current domain and unlocks the mutex. When this domain is woken up again (when the wait call returns), it holds the lock on mutex. The domain tries to read the contents of the stack again. If the pop operation sees that the stack is non-empty, it updates the contents to the tail of the old list, and returns the head.
The use of mutex to control access to the shared resource contents introduces sufficient synchronisation between multiple domains using the stack. Hence, there are no data races when multiple domains use the stack in parallel.
|
### 5.1 Interaction with systhreads
How do systhreads interact with domains? The systhreads created on a particular domain remain pinned to that domain. Only one systhread at a time is allowed to run OCaml code on a particular domain. However, systhreads belonging to a particular domain may run C library or system code in parallel. Systhreads belonging to different domains may execute in parallel.
When using systhreads, the thread created for executing the computation given to Domain.spawn is also treated as a systhread. For example, the following program creates in total two domains (including the initial domain) with two systhreads each (including the initial systhread for each of the domains).
(* dom_thr.ml *)
let m = Mutex.create ()
let r = ref None (* protected by m *)
let task () =
let my_thr_id = Thread.(id (self ())) in
let my_dom_id :> int = Domain.self () in
Mutex.lock m;
begin match !r with
| None ->
Printf.printf "Thread %d running on domain %d saw initial write\n%!"
my_thr_id my_dom_id
| Some their_thr_id ->
Printf.printf "Thread %d running on domain %d saw the write by thread %d\n%!"
my_thr_id my_dom_id their_thr_id;
end;
r := Some my_thr_id;
Mutex.unlock m
let task' () =
let t = Thread.create task () in
task ();
Thread.join t
let main () =
let d = Domain.spawn task' in
task' ();
Domain.join d
let _ = main ()
|
### 5.1 Interaction with systhreads
$ ocamlopt -I +threads unix.cmxa threads.cmxa -o dom_thr.exe dom_thr.ml
$ ./dom_thr.exe
Thread 1 running on domain 1 saw initial write
Thread 0 running on domain 0 saw the write by thread 1
Thread 2 running on domain 1 saw the write by thread 0
Thread 3 running on domain 0 saw the write by thread 2
This program uses a shared reference cell protected by a mutex to communicate between the different systhreads running on two different domains. The systhread identifiers uniquely identify systhreads in the program. The initial domain gets the domain id and the thread id as 0. The newly spawned domain gets domain id as 1.
|
## 6 Interaction with C bindings
During parallel execution with multiple domains, C code running on a domain may run in parallel with any C code running in other domains even if neither of them has released the “domain lock”. Prior to OCaml 5.0, C bindings may have assumed that if the OCaml runtime lock is not released, then it would be safe to manipulate global C state (e.g. initialise a function-local static value). This is no longer true in the presence of parallel execution with multiple domains.
|
## 7 Atomics
Mutex, condition variables and semaphores are used to implement blocking synchronisation between domains. For non-blocking synchronisation, OCaml provides [Atomic](../5.2/api/Atomic.html) variables. As the name suggests, non-blocking synchronisation does not provide mechanisms for suspending and waking up domains. On the other hand, primitives used in non-blocking synchronisation are often compiled to atomic read-modify-write primitives that the hardware provides. As an example, the following program increments a non-atomic counter and an atomic counter in parallel.
(\* incr.ml \*) let twice_in_parallel f = let d1 = Domain.spawn f in let d2 = Domain.spawn f in Domain.join d1; Domain.join d2 let plain_ref n = let r = ref 0 in let f () = for \_i=1 to n do incr r done in twice_in_parallel f; Printf.printf "Non-atomic ref count: %d\\n" !r let atomic_ref n = let r = Atomic.make 0 in let f () = for \_i=1 to n do Atomic.incr r done in twice_in_parallel f; Printf.printf "Atomic ref count: %d\\n" (Atomic.get r) let main () = let n = try int_of_string Sys.argv.(1) with \_ -> 1 in plain_ref n; atomic_ref n let \_ = main ()
$ ocamlopt -o incr.exe incr.ml
$ ./incr.exe 1_000_000
Non-atomic ref count: 1187193
Atomic ref count: 2000000
Observe that the result from using the non-atomic counter is lower than what one would naively expect. This is because the non-atomic incr function is equivalent to:
let incr r = let curr = !r in r := curr + 1
|
## 7 Atomics
Observe that the load and the store are two separate operations, and the increment operation as a whole is not performed atomically. When two domains execute this code in parallel, both of them may read the same value of the counter curr and update it to curr + 1. Hence, instead of two increments, the effect will be that of a single increment. On the other hand, the atomic counter performs the load and the store atomically with the help of hardware support for atomicity. The atomic counter returns the expected result.
The atomic variables can be used for low-level synchronisation between the domains. The following example uses an atomic variable to exchange a message between two domains.
let r = Atomic.make None let sender () = Atomic.set r (Some "Hello") let rec receiver () = match Atomic.get r with \| None -> Domain.cpu_relax (); receiver () \| Some m -> print_endline m let main () = let s = Domain.spawn sender in let d = Domain.spawn receiver in Domain.join s; Domain.join d let \_ = main ()
Hello val r : string option Atomic.t = \<abstr> val sender : unit -> unit = \<fun\> val receiver : unit -> unit = \<fun\> val main : unit -> unit = \<fun\>
While the sender and the receiver compete to access r, this is not a data race since r is an atomic reference.
|
### 7.1 Lock-free stack
The Atomic module is used to implement non-blocking, lock-free data structures. The following program implements a lock-free stack.
module Lockfree_stack : sig type 'a t val make : unit -> 'a t val push : 'a t -> 'a -> unit val pop : 'a t -> 'a option end = struct type 'a t = 'a list Atomic.t let make () = Atomic.make \[\] let rec push r v = let s = Atomic.get r in if Atomic.compare_and_set r s (v::s) then () else (Domain.cpu_relax (); push r v) let rec pop r = let s = Atomic.get r in match s with \| \[\] -> None \| x::xs -> if Atomic.compare_and_set r s xs then Some x else (Domain.cpu_relax (); pop r) end
The atomic stack is represented by an atomic reference that holds a list. The push and pop operations use the compare_and_set primitive to attempt to atomically update the atomic reference. The expression compare_and_set r seen v sets the value of r to v if and only if its current value is physically equal to seen. Importantly, the comparison and the update occur atomically. The expression evaluates to true if the comparison succeeded (and the update happened) and false otherwise.
If the compare_and_set fails, then some other domain is also attempting to update the atomic reference at the same time. In this case, the push and pop operations call Domain.cpu_relax to back off for a short duration allowing competing domains to make progress before retrying the failed operation. This lock-free stack implementation is also known as Treiber stack.
------------------------------------------------------------------------
|
### 7.1 Lock-free stack
[« Advanced examples with classes and modules](advexamples.html)[Memory model: The hard bits »](memorymodel.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Memory model: The hard bits
Source: https://ocaml.org/manual/5.2/memorymodel.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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.