`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`.

Since: 4.11

val `fold_left`: `f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc`
`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (init b1) b2) ...) bn`.

val `fold_right`: `f:('a -> 'acc -> 'acc) -> 'a list -> init:'acc -> 'acc`
`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not
tail-recursive.

Iterators on two lists

val `iter2`: `f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit`
`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`.
**Raises** `Invalid_argument` if the two lists are determined to have different lengths.

val `map2`: `f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list`
`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`.
**Raises** `Invalid_argument` if the two lists are determined to have different lengths.

val `rev_map2`: `f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list`
`rev_map2 ~f 11 12` gives the same result as `ListLabels.rev[28.32]`
(`ListLabels.map2[28.32] f 11 12`), but is more efficient.

val `fold_left2`:
`f:('acc -> 'a -> 'b -> 'acc) -> init:'acc -> 'a list -> 'b list -> 'acc`
`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (init a1 b1) a2 b2) ...) an bn`.
**Raises** `Invalid_argument` if the two lists are determined to have different lengths.

val `fold_right2`:
`f:('a -> 'b -> 'acc -> 'acc) -> 'a list -> 'b list -> init:'acc -> 'acc`
`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`.
**Raises** `Invalid_argument` if the two lists are determined to have different lengths. Not tail-recursive.
• @.: flush the pretty-printer and split the line, as with print_newline().

• @<n>: print the following item as if it were of length n. Hence, printf "@<0>%s" arg prints arg as a zero length string. If @<n> is not followed by a conversion specification, then the following character of the format is printed as if it were of length n.

• @{: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the < character, followed by an optional string specification, and the closing > character. The string specification is any character string that does not contain the closing character '>',. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions Format.open_stag [29.23] and Format.close_stag [29.23].

• @}: close the most recently opened semantic tag.

• @?: flush the pretty-printer as with print_flush(). This is equivalent to the conversion %!.

• @\n: force a newline, as with force_newline(), not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box.

Note: To prevent the interpretation of a @ character as a pretty-printing indication, escape it with a % character. Old quotation mode @@ is deprecated since it is not compatible with formatted input interpretation of character '@'.

Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box(); print_string "x ="; print_space(); print_int 1; close_box(); print_newline()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box.

val printf: ('a, formatter, unit) format -> 'a
Same as fprintf above, but output on get_std_formatter().

It is defined similarly to `fun fmt -> fprintf (get_std_formatter()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with `Format.print_flush[29.23]`.

val eprintf: ('a, formatter, unit) format -> 'a
Same as fprintf above, but output on get_err_formatter().

It is defined similarly to `fun fmt -> fprintf (get_err_formatter()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with `Format.print_flush[29.23]`.

val sprintf: ('a, unit, string) format -> 'a
Same as printf above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of each call to sprintf. Note that if your format string contains a %a, you should use asprintf.

In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter()` to get the final result.
## List scanning

val `for_all`: `f:('a -> bool) -> 'a list -> bool`

`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty.

val `exists`: `f:('a -> bool) -> 'a list -> bool`

`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty.

val `for_all2`: `f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool`

Same as `ListLabels.for_all[28.32]`, but for a two-argument predicate.

**Raises** `Invalid_argument` if the two lists are determined to have different lengths.

val `exists2`: `f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool`

Same as `ListLabels.exists[28.32]`, but for a two-argument predicate.

**Raises** `Invalid_argument` if the two lists are determined to have different lengths.

val `mem`: `'a -> set:'a list -> bool`

`mem a ~set` is true if and only if `a` is equal to an element of `set`.

val `memq`: `'a -> set:'a list -> bool`

Same as `ListLabels.mem[28.32]`, but uses physical equality instead of structural equality to compare list elements.

## List searching

val `find`: `f:('a -> bool) -> 'a list -> 'a`

`find ~f 1` returns the first element of the list `1` that satisfies the predicate `f`.

**Raises** `Not_found` if there is no value that satisfies `f` in the list `1`.

val `find_opt`: `f:('a -> bool) -> 'a list -> 'a option`

`find ~f 1` returns the first element of the list `1` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `1`.

**Since:** 4.05

val `find_index`: `f:('a -> bool) -> 'a list -> int option`

`find_index ~f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element.

It returns `None` if there is no such element.

**Since:** 5.1
Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string.

`val asprintf : ('a, formatter, unit, string) format4 -> 'a`

Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions.

**Since:** 4.01

`val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a`

Same as `Format.fprintf[29.23]`, except the formatter is the last argument. `dprintf "..."` a b c is a function of type `formatter -> unit` which can be given to a format specifier `%t`.

This can be used as a replacement for `Format.asprintf[29.23]` to delay formatting decisions. Using the string returned by `Format.asprintf[29.23]` in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. `Format.dprintf[29.23]` allows delay of formatting decisions until the final formatting context is known. For example:

```hml
let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in
...
Formatprintf "@[<v>%t@]" t
```

**Since:** 4.08

`val ifprintf : formatter -> ('a, formatter, unit) format -> 'a`

Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.

**Since:** 3.10

Formatted Pretty-Printing with continuations.

`val kfprintf :`
`  (formatter -> 'a) ->`
`  formatter -> ('b, formatter, unit, 'a) format4 -> 'b`

Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing.

`val kdprintf :`
`  ((formatter -> unit) -> 'a) ->`
`  ('b, formatter, unit, 'a) format4 -> 'b`

Same as `Format.dprintf[29.23]` above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing.

**Since:** 4.08
```hkl
val find_map : f:('a -> 'b option) -> 'a list -> 'b option
```

`find_map ~f 1` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist.

**Since:** 4.10

```hkl
val find_mapi : f:(int -> 'a -> 'b option) -> 'a list -> 'b option
```

Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.

**Since:** 5.1

```hkl
val filter : f:('a -> bool) -> 'a list -> 'a list
```

`filter ~f 1` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved.

```hkl
val find_all : f:('a -> bool) -> 'a list -> 'a list
```

`find_all` is another name for `ListLabels.filter[28.32]`.

```hkl
val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list
```

Same as `ListLabels.filter[28.32]`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.

**Since:** 4.11

```hkl
val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
```

`partition ~f 1` returns a pair of lists `(11, 12)`, where `11` is the list of all the elements of `l` that satisfy the predicate `f`, and `12` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved.

```hkl
val partition_map :
```

`f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list`

`partition_map f 1` returns a pair of lists `(11, 12)` such that, for each element `x` of the input list `l`:

* if `f x` is `Left y1`, then `y1` is in `l1`, and

* if `f x` is `Right y2`, then `y2` is in `l2`.

The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`.

In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f 1`.

**Since:** 4.12
```h
val ikfprintf :
    (formatter -> 'a) ->
    formatter -> ('b, formatter, unit, 'a) format4 -> 'b
```

Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.

**Since: 3.12**

```h
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
```

Same as `sprintf` above, but instead of returning the string, passes it to the first argument.

```h
val kassprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b
```

Same as `asprintf` above, but instead of returning the string, passes it to the first argument.

**Since: 4.03**

## Examples

A few warmup examples to get an idea of how Format is used.

We have a list `l` of pairs `(int * bool)`, which the `topleft` prints for us:

```h
# let l = List.init 20 (fun n -> n, n mod 2 = 0)
val l : (int * bool) list =
  [(0, true); (1, false); (2, true); (3, false); (4, true); (5, false);
   (6, true); (7, false); (8, true); (9, false); (10, true); (11, false);
   (12, true); (13, false); (14, true); (15, false); (16, true); (17, false);
   (18, true); (19, false)]
```

If we want to print it ourself without the toplevel magic, we can try this:

```h
# let pp_pair out (x,y) = Format.fprintf out "(%d, %b)" x y
val pp_pair : Format formatter -> int * bool -> unit = <fun>
# Formatprintf "l: [[<hov>%a@]]@." Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out ";@ ") pp_pair) l
l: [(0, true); (1, false); (2, true); (3, false); (4, true); (5, false);
   (6, true); (7, false); (8, true); (9, false); (10, true); (11, false);
   (12, true); (13, false); (14, true); (15, false); (16, true);
   (17, false); (18, true); (19, false)]
```

What this does, briefly, is:

* `pp_pair` prints a pair `bool*int` surrounded in `(" ")`. It takes a formatter (into which formatting happens), and the pair itself. When printing is done it returns `()`.

* `Formatprintf "l = [[<hov>%a@]]@." ... l` is like `printf`, but with additional formatting instructions (denoted with `"@"`). The pair `"[[<hov>"` and `"@]"` is a "horizontal-or-vertical box".
Association lists

val assoc : 'a -> ('a * 'b) list -> 'b

assoc a 1 returns the value associated with key a in the list of pairs 1. That is, assoc a [
...; (a,b); ...] = b if (a,b) is the leftmost binding of a in list 1.

Raises Not_found if there is no value associated with a in the list 1.

val assoc_opt : 'a -> ('a * 'b) list -> 'b option

assoc_opt a 1 returns the value associated with key a in the list of pairs 1. That is,
assoc_opt a [ ... ; (a,b) ; ... ] = Some b if (a,b) is the leftmost binding of a in list 1.

Returns None if there is no value associated with a in the list 1.

Since: 4.05

val assq : 'a -> ('a * 'b) list -> 'b

Same as ListLabels.assoc[28.32], but uses physical equality instead of structural equality to compare keys.

val assq_opt : 'a -> ('a * 'b) list -> 'b option

Same as ListLabels.assoc_opt[28.32], but uses physical equality instead of structural
equality to compare keys.

Since: 4.05

val mem: 'a -> map:('a * 'b) list -> bool

Same as ListLabels.assoc[28.32], but simply return true if a binding exists, and false if no bindings exist for the given key.

val mem_assq : 'a -> map:('a * 'b) list -> bool

Same as ListLabels.mem[28.32], but uses physical equality instead of structural
equality to compare keys.

val remove assoc : 'a -> ('a * 'b) list -> ('a * 'b) list

remove assoc a 1 returns the list of pairs 1 without the first pair with key a, if any. Not tail-recursive.

val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list

Same as ListLabels.remove[28.32], but uses physical equality instead of structural
equality to compare keys. Not tail-recursive.

Lists of pairs

val split : ('a * 'b) list -> 'a list * 'b list

Transform a list of pairs into a pair of lists: split [(a1,b1); ...; (an,bn)] is ([a1;
...; an], [b1; ...; bn]). Not tail-recursive.
* "@." ends formatting with a newline. It is similar to "\n" but is also aware of the `Format formatter`'s state. Do not use "\n" with `Format`.

* "%a" is a formatting instruction, like "%d" or "%s" for `printf`. However, where "%d" prints an integer and "%s" prints a string, "%a" takes a printer (of type `Format formatter -> 'a -> unit`) and a value (of type `'a`) and applies the printer to the value. This is key to compositionality of printers.

* We build a list printer using `Format.pp_print_list ~pp_sep: (...) pp_pair`. `pp_print_list` takes an element printer and returns a list printer. The `?pp_sep` optional argument, if provided, is called in between each element to print a separator.

* Here, for a separator, we use `(fun out () -> Format.fprintf out ";@ ")`. It prints ";", and then "@" which is a breaking space (either it prints " ", or it prints a newline if the box is about to overflow). This "@" is responsible for the list printing splitting into several lines.

If we omit "@", we get an ugly single-line print:

```h
# Format.fprintf "1: [[<hov>%a@]]@."
Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out "; ") pp_pair) 1
1: [(0, true); (1, false); (2, true); (* ... *); (18, true); (19, false)]
- : unit = ()
```

Generally, it is good practice to define custom printers for important types in your program. If, for example, you were to define basic geometry types like so:

```h
type point = {
    x: float;
    y: float;
}

type rectangle = {
    ll: point; (* lower left *)
    ur: point; (* upper right *)
}
```

For debugging purpose, or to display information in logs, or on the console, it would be convenient to define printers for these types. Here is an example of to do it. Note that "%.3f" is a `float` printer up to 3 digits of precision after the dot; "%f" would print as many digits as required, which is somewhat verbose; "%h" is an hexadecimal float printer.

```h
let pp_point out (p:point) =
    Format.fprintf out "{{ @[x=%.3f;@ y=%.3f@] }}" p.x p.y

let pprectangle out (r:rectangle) =
    Format.fprintf out "{{ @[ll=%a;@ ur=%a@] }}"
```
```hkl
val combine : 'a list -> 'b list -> ('a * 'b) list
```

Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is
[(a1,b1); ...; (an,bn)].

Raises Invalid_argument if the two lists have different lengths. Not tail-recursive.

## Sorting

```hkl
val sort : cmp: ('a -> 'a -> int) -> 'a list -> 'a list
```

Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, `compare[27.2]` is a suitable comparison function. The resulting list is sorted in increasing order. `ListLabels.sort[28.32]` is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space.

The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.

```hkl
val stable_sort : cmp: ('a -> 'a -> int) -> 'a list -> 'a list
```

Same as `ListLabels.sort[28.32]`, but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order).

The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.

```hkl
val fast_sort : cmp: ('a -> 'a -> int) -> 'a list -> 'a list
```

Same as `ListLabels.sort[28.32]` or `ListLabels.stable_sort[28.32]`, whichever is faster on typical input.

```hkl
val sort_uniq : cmp: ('a -> 'a -> int) -> 'a list -> 'a list
```

Same as `ListLabels.sort[28.32]`, but also remove duplicates.

Since: 4.03

```hkl
val merge : cmp: ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
```

Merge two lists: Assuming that 11 and 12 are sorted according to the comparison function `cmp`, `merge ~cmp 11 12` will return a sorted list containing all the elements of 11 and 12. If several elements compare equal, the elements of 11 will be before the elements of 12. Not tail-recursive (sum of the lengths of the arguments).

## Lists and Sequences

```hkl
val to_seq : 'a list -> 'a Seq.t
```

Iterate on the list.

Since: 4.07
pp_point r.ll pp_point r.ur

In the .mli file, we could have:

val pp_point : Format formatter -> point -> unit

val pprectangle : Format formatter -> rectangle -> unit

These printers can now be used with "%a" inside other printers.

# Formateer "some rectangle: %a@."
(Format.pp_print_option pprectangle)
(Some {ll={x=1.; y=2.}; ur={x=42.; y=500.12345}})
some rectangle: { l={ x=1.000; y=2.000 }; ur={ x=42.000; y=500.123 } }

# Formateer "no rectangle: %a@."
(Format.pp_option pprectangle)
None
no rectangle:

See how we combine `pp_print_option` (option printer) and our newly defined rectangle printer, like we did with `pp_print_list` earlier.

For a more extensive tutorial, see

"Using the Format module" [https://caml.inria.fr/resources/doc/guides/format.en.html].

A final note: the `Format` module is a starting point. The OCaml ecosystem has libraries that make formatting easier and more expressive, with more combinators, more concise names, etc. An example of such a library is `Fmt` [https://erratique.ch/software/fmt].

Automatic deriving of pretty-printers from type definitions is also possible, using
https://github.com/ocaml-ppx/ppx_deriving[ppx_deriving.show] or similar ppx derivers.

## 29.24 Module Fun : Function manipulation.

See the examples [29.48] below.

Since: 4.08

### Combinators

val id : 'a -> 'a
id is the identity function. For any argument x, id x is x.

val const : 'a -> 'b -> 'a
const c is a function that always returns the value c. For any argument x, (const c) x is c.

val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c
`val of_seq : 'a Seq.t -> 'a list`

Create a list from a sequence.

**Since: 4.07**

## 28.33 Module Map : Association tables over ordered types.

This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map.

For instance:

```python
module IntPairs =
    struct
        type t = int * int
        let compare (x0,y0) (x1,y1) =
            match Stdlib comparisons
                0 -> Stdlib compare y0 y1
                | c -> c
            end

module PairsMap = Map.Make(IntPairs)

let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
```

This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`.

```python
module type OrderedType =
    sig
        type t

        The type of the map keys.

        val compare : t -> t -> int
```

A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function `compare[27.2]`.

```python
end

Input signature of the functor `Map.Make[28.33]`.
```
`compose` `f` `g` is a function composition of applying `g` then `f`. For any arguments `f`, `g`, and `x`, `compose f g x` is `f` (`g x`).

Since: 5.2

`val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c`

`flip` `f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`.

`val negate : ('a -> bool) -> 'a -> bool`

`negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is not (`p x`).

## Exception handling

`val protect : finally: (unit -> unit) -> (unit -> 'a) -> 'a`

`protect ~finally work` invokes `work()` and then `finally()` before `work()` returns with its value or an exception. In the latter case the exception is re-raised after `finally()`. If `finally()` raises an exception, then the exception `Fun.Finally_Raised[29.24]` is raised instead.

`protect` can be used to enforce local invariants whether `work()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally()` such as `Out_of_memory[28.2]`, `Stack_overflow[28.2]`, or asynchronous exceptions raised by signal handlers (e.g. `Sys.Break[29.60]`).

Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work()` will be lost in the event of a `Fun.Finally_Raised[29.24]` exception. Therefore, one should make sure to handle those inside the `finally`.

### exception Finally_Raised of exn

`Finally_Raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_Raised` exception except as part of a catch-all handler.

## Examples

### Combinators

`Combinators[29.24]` provide a lightweight and sometimes more readable way to create anonymous functions, best used as short-lived arguments rather than standalone definitions. The examples below will demonstrate this mainly with the `List[29.33]` module.
module type S =
sig

## Maps

type key

The type of the map keys.

type !+'a t

The type of maps from type `key` to type `'a`.

val empty : 'a t

The empty map.

val add : key -> 'a -> 'a t -> 'a t

`add` key `data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears.

**Before 4.03** Physical equality was not ensured.

val add_to_list : key -> 'a -> 'a list t -> 'a list t

`add_to_list` key `data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find` key `m` if `key` was bound in `m` and `[v]` otherwise.

**Since: 5.1**

val update : key -> ('a option -> 'a option) -> 'a t -> 'a t

`update` key `f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`).

**Since: 4.06**

val singleton : key -> 'a -> 'a t

`singleton` `x y` returns the one-element map that contains a binding `y` for `x`.

**Since: 3.12**

val remove : key -> 'a t -> 'a t
29.24.1 id[29.24]

List.init[29.33] with the index itself

# List.init 3 Fun.id;;
- : int list = [0; 1; 2]

Using List.filter_map[29.33] on an int option list to filter out None[??] elements

# List.filter_map Fun.id [None; Some 2; Some 3; None; Some 5];;
- : int list = [2; 3; 5]

Conditionally dispatching functions of type `foo -> foo` or taking them as arguments is another place where `id` may be useful. Consider a primitive logging function which prints a string but gives its user the option to preformat the string before printing, e.g. to insert a time-stamp

let log ?(preformat : string -> string = Fun.id) message =
    print_endline (preformat message)

Whenever we may build up closures, `id` is often used for the base-case as a no-op. Consider a function which chains a list of unary functions:

let rec chain = function
| [] -> Fun.id
| f :: fs -> fun x -> f (chain fs x)

29.24.2 const[29.24]

`List.init[29.33]` a list of zeros

# List.init 3 (Funez const 0);;
- : int list = [0; 0; 0]

An allow-all predicate that could be passed to any filtering function e.g. `List.filter[29.33]` to disable filtration and get back all values

# List.filter (Funez const true) [1; 2; 3];;
- : int list = [1; 2; 3]

Note that applying `const (...)` evaluates the expression ` (...)` once, and returns a function that only has the result of this evaluation. To demonstrate this, consider if ` (...)` was a call to `Randombool[29.49]()`:

`List.init n (Funez const (Randombool()))` for any `n > 0` will have *exactly two* possible outcomes,
`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`).

**Before 4.03** Physical equality was not ensured.

```hkl
val merge :
  (key -> 'a option -> 'b option -> 'c option) ->
  'a t -> 'b t -> 'c t
```

`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None = None`. None = None.

**Since:** 3.12

```hkl
val union : (key -> 'a -> 'a -> 'a option) ->
  'a t -> 'a t -> 'a t
```

`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where

* `f' _key None None = None`

* `f' _key (Some v) None = Some v`

* `f' _key None (Some v) = Some v`

* `f' key (Some v1) (Some v2) = f key v1 v2`

**Since:** 4.03

```hkl
val cardinal : 'a t -> int
```

Return the number of bindings of a map.

**Since:** 3.12

## Bindings

```hkl
val bindings : 'a t -> (key * 'a) list
```

Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord compares`, where `Ord` is the argument given to `Map.Make[28.33]`.

**Since:** 3.12

```hkl
val min_bindig : 'a t -> key * 'a
```
* `[true; true; ...; true]`

* `[false; false; ...; false]`

whereas `List.init n` (`fun _ -> Randombool()`) will have $2^n$ possible outcomes, because the randomness effect is performed with every element.

For more real-world uses, consider `String.spellcheck[29.58]` with a constant max distance of 2, instead of the default variable max distance

```python
let spellcheck known_words word =
    let dict_iter yield = List.iter yield known_words in
    String.spellcheck ~max_dist:(Funiones const 2) dict_iter word
```

### 29.24.3 flip[29.24]

Useing `flip` to reverse the comparator passed to `List.sort[29.33]`, which sorts in the opposite order

```python
# List.sort (Fun们的 flip Int compares) [5; 3; 9; 0; 1; 6; 8];
- : int list = [9; 8; 6; 5; 3; 1; 0]
```

Reversing a list by accumulating a new list using `List.fold_left[29.33]`, which expects the accumulator to be the first argument of the function passed to it. We pass `List.consn[29.33]` which has the list as the second argument, so `flip` is useful here

```python
# List.fold_left (Fun's flip List.consn) [] [1; 2; 3];
- : int list = [3; 2; 1]
```

Interestingly, `flip` can work with functions that aren't binary, by flipping the first two arguments and leaving the rest in order. This is because a function that takes `n+2` arguments is, conceptually, a binary function which returns a function that takes `n` arguments. Given a function `f : a -> b -> c -> d`:

* `flip f` will have type `b -> a -> c -> d`

* `fun x -> flip (f x)` will have type `a -> c -> b -> d`

Using `flip` with non-binary functions like this is discouraged, for its negative impact on readability and reasoning.

### 29.24.4 negate[29.24]

Mainly used for reversing a predicate in a function which expects one, like `List.find_all[29.33]` and similar functions

Finding all lists which are *not* empty using `List.is_empty[29.33]`
Return the binding with the smallest key in a given map (with respect to the `Ord compares ordering), or raise `Not_found` if the map is empty.

**Since: 3.12**

`val min_bindig_opt: 'a t -> (key * 'a) option`

Return the binding with the smallest key in the given map (with respect to the `Ord compares ordering), or `None` if the map is empty.

**Since: 4.05**

`val max_bindig: 'a t -> key * 'a`

Same as `Map.S.min_bindig` [28.33], but returns the binding with the largest key in the given map.

**Since: 3.12**

`val max_bindig_opt: 'a t -> (key * 'a) option`

Same as `Map.S.min_bindig_opt` [28.33], but returns the binding with the largest key in the given map.

**Since: 4.05**

`val choose: 'a t -> key * 'a`

Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.

**Since: 3.12**

`val choose_opt: 'a t -> (key * 'a) option`

Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.

**Since: 4.05**

## Searching

`val find: key -> 'a t -> 'a`

`find` `x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists.

`val find_opt: key -> 'a t -> 'a option`

`find_opt` `x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists.

**Since: 4.05**

`val find_first: (key -> bool) -> 'a t -> key * 'a`
# List.find_all (Fun.negate List.is_empty) [[0]; [1; 2; 3]; []; [4; 5]];;
- : int list list = [[0]; [1; 2; 3]; [4; 5]]

From a given list of paths, finding all paths which are *not* occupied using `Sys.file_exists` [29.60]

# List.find_all (Fun.negate Sys.file_exists);;
- : string list -> string list = <fun>

### 29.24.5 compose[29.24]

`List.map` [29.33] on pair elements with a function on the second element

# List.map (Fun.create String.length snd) [1, "one"; 2, "two"; 3, "three"];;
- : int list = [3; 3; 5]

A potential implementation of `Fun.negate` [29.24]

let negate f = Fun.create not f

From the `chain` example [29.24.1], `compose` could have been used in the recursive branch

let rec chain = function
| [] -> Fun.id
| f :: fs -> Fun.create f (chain fs)

Or even more concisely

let chain fs = List-fold_right Fun.create fs Fun.id

From the `spellcheck` example [29.24.3], `compose` and `flip` could be used to condense the function definition so it becomes

# Fun.create
(String.spellcheck ~max_dist:(Funoler const 2))
(Fun.flop List.iter)
;;
- : string list -> string -> string list = <fun>

As can be seen here, this heavily impacts readability and the ability to reason about the function. Both `String.spellcheck` and `Fun.flop` are not unary, so there is a non-trivial interaction with partial-application in this definition.

Heavy use of these combiners in OCaml is generally discouraged, not only because they can quickly impact readability and reasoning, but also because the produced functions are often in value
`find_first` f m, where f is a monotonically increasing function, returns the binding of m with the lowest key k such that f k, or raises `Not_found` if no such key exists.

For example, `find_first (fun k -> Ord compares k x >= 0) m` will return the first binding k, v of m where `Ord comparisons k x >= 0` (intuitively: k >= x), or raise `Not_found` if x is greater than any element of m.

**Since:** 4.05

`val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option`

`find_first_opt` f m, where f is a monotonically increasing function, returns an option containing the binding of m with the lowest key k such that f k, or `None` if no such key exists.

**Since:** 4.05

`val find_last : (key -> bool) -> 'a t -> key * 'a`

`find_last` f m, where f is a monotonically decreasing function, returns the binding of m with the highest key k such that f k, or raises `Not_found` if no such key exists.

**Since:** 4.05

`val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option`

`find_last_opt` f m, where f is a monotonically decreasing function, returns an option containing the binding of m with the highest key k such that f k, or `None` if no such key exists.

**Since:** 4.05

## Traversing

`val iter : (key -> 'a -> unit) -> 'a t -> unit`

`iter` f m applies f to all bindings in map m. f receives the key as first argument, and the associated value as second argument. The bindings are passed to f in increasing order with respect to the ordering over the type of the keys.

`val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc`

`fold` f m `init` computes (`f` kN `dN` ... (`f` k1 `d1` `init`)...), where k1 ... kN are the keys of all bindings in m (in increasing order), and `d1` ... `dN` are the associated data.

## Transforming

`val map : ('a -> 'b) -> 'a t -> 'b t`
form, thus subject to the Value Restriction (see the manual section 6.1.2).

## 29.25 Module Gc: Memory management control and statistics; finalised values.

type stat =

{ minor_words : float ;

Number of words allocated in the minor heap since the program was started.

promoted_words : float ;

Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started.

major_words : float ;

Number of words allocated in the major heap, including the promoted words, since the program was started.

minor_collections : int ;

Number of minor collections since the program was started.

major_collections : int ;

Number of major collection cycles completed since the program was started.

heap_words : int ;

Total size of the major heap, in words.

heap_chunks : int ;

Number of contiguous pieces of memory that make up the major heap. This metric is currently not available in OCaml 5: the field value is always 0.

live_words : int ;

Number of words of live data in the major heap, including the header words.

Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call `Gc.full_major[29.25]` (or `Gc.compact[29.25]`) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to `Gc.full_major[29.25]` will not reclaim values that have a finaliser from `Gc_finalise[29.25]` (this does not apply to `Gc_finalise_last[29.25]`). If this caveat matters, simply call `Gc.full_major[29.25]` twice instead of once.

live_blocks : int ;

Number of live blocks in the major heap.

See `live_words` for a caveat about what "live" means.

free_words : int ;
`map` f m returns a map with same domain as m, where the associated value a of all bindings of m has been replaced by the result of the application of f to a. The bindings are passed to f in increasing order with respect to the ordering over the type of the keys.

```hkl
val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
```

Same as `Map.S.map`[28.33], but the function receives as arguments both the key and the associated value for each binding of the map.

```hkl
val filter : (key -> 'a -> bool) -> 'a t -> 'a t
```

`filter` f m returns the map with all the bindings in m that satisfy predicate p. If every binding in m satisfies f, m is returned unchanged (the result of the function is then physically equal to m)

**Before 4.03** Physical equality was not ensured.

**Since:** 3.12

```hkl
val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t
```

`filter_map` f m applies the function f to every binding of m, and builds a map from the results. For each binding (k, v) in the input map:

* if f k v is `None` then k is not in the result,

* if f k v is `Some v` then the binding (k, v') is in the output map.

For example, the following function on maps whose values are lists

```hkl
filter_map
    (fun _k li -> match li with [] -> None | _::tl -> Some tl)
m
```

drops all bindings of m whose value is an empty list, and pops the first element of each value that is non-empty.

**Since:** 4.11

```hkl
val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
```

`partition` f m returns a pair of maps (`m1`, `m2`), where `m1` contains all the bindings of m that satisfy the predicate f, and `m2` is the map with all the bindings of m that do not satisfy f.

**Since:** 3.12

```hkl
val split : key -> 'a t -> 'a t * 'a option * 'a t
```

`split` x m returns a triple (`l`, `data`, `r`), where `l` is the map with all the bindings of m whose key is strictly less than x; `r` is the map with all the bindings of m whose key is strictly greater than x; `data` is `None` if m contains no binding for x, or `Some v` if m binds v to x.

**Since:** 3.12
Number of words in the free list.

`free_blocks : int ;`

Number of blocks in the free list. This metric is currently not available in OCaml 5:
the field value is always 0.

`largest_free : int ;`

Size (in words) of the largest block in the free list. This metric is currently not
available in OCaml 5: the field value is always 0.

`fragments : int ;`

Number of wasted words due to fragmentation. These are 1-words free blocks placed
between two live blocks. They are not available for allocation.

`compactions : int ;`

Number of heap compactions since the program was started.

`top_heap_words : int ;`

Maximum size reached by the major heap, in words.

`stack_size : int ;`

Current size of the stack, in words. This metric is currently not available in OCaml 5:
the field value is always 0.

Since: 3.12

`forced_major_collections : int ;`

Number of forced full major collections completed since the program was started.

Since: 4.12

}

The memory management counters are returned in a `stat` record. These counters give values for the whole program.

The total amount of memory allocated by the program since it was started is (in words)
`minor_words` + `major_words` - `promoted_words`. Multiply by the word size (4 on a 32-bit
machine, 8 on a 64-bit machine) to get the number of bytes.

`type control =`

{ minor_heap_size : int ;

The size (in words) of the minor heap. Changing this parameter will trigger a minor
collection. The total size of the minor heap used by this program is the sum of the heap
sizes of the active domains. Default: 256k.

`major_heap_increment : int ;`

How much to add to the major heap when increasing it. If this number is less than or
equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will
double the heap size at each increase). If it is more than 1000, it is a fixed number of
words that will be added to the heap.

This field is currently not available in OCaml 5: the field value is always 0.
## Predicates and comparisons

`val is_empty : 'a t -> bool`

Test whether a map is empty or not.

`val mem : key -> 'a t -> bool`

`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise.

`val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool`

`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys.

`val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int`

Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps.

`val for_all : (key -> 'a -> bool) -> 'a t -> bool`

`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. **Since:** 3.12

`val exists : (key -> 'a -> bool) -> 'a t -> bool`

`exists f m` checks if at least one binding of the map satisfies the predicate `f`. **Since:** 3.12

## Converting

`val to_list : 'a t -> (key * 'a) list`

`to_list m` is `Map.S.bindings[28.33] m`. **Since:** 5.1

`val of_list : (key * 'a) list -> 'a t`

`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). **Since:** 5.1

`val to_seq : 'a t -> (key * 'a) Seq.t`

Iterate on the whole map, in ascending order of keys. **Since:** 4.07
`space_overhead : int ;`

The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120.

`verbose : int ;`

This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events:

* `0x0001` Start and end of major GC cycle.

* `0x0002` Minor collection and major GC slice.

* `0x0004` Growing and shrinking of the heap.

* `0x0008` Resizing of stacks and memory manager tables.

* `0x0010` Heap compaction.

* `0x0020` Change of GC parameters.

* `0x0040` Computation of major GC slice size.

* `0x0080` Calling of finalisation functions.

* `0x0100` Bytecode executable and shared library search at start-up.

* `0x0200` Computation of compaction-triggering condition.

* `0x0400` Output GC statistics at program exit.

* `0x0800` GC debugging messages.

* `0x1000` Address space reservation changes. Default: 0.

`max_overhead : int ;`

Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead` >= 1000000, compaction is never triggered.

This field is currently not available in OCaml 5: the field value is always 0.

`stack_limit : int ;`

The maximum size of the fiber stacks (in words). Default: 128M.

`allocation_policy : int ;`

The policy used for allocating in the major heap.

This field is currently not available in OCaml 5: the field value is always 0.

Prior to OCaml 5.0, possible values were 0, 1 and 2.

* `0` was the next-fit policy
```hkl
val to_rev_seq : 'a t -> (key * 'a) Seq.t
```

Iterate on the whole map, in descending order of keys

**Since: 4.12**

```hkl
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
```

`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above.

**Since: 4.07**

```hkl
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
```

Add the given bindings to the map, in order.

**Since: 4.07**

```hkl
val of_seq : (key * 'a) Seq.t -> 'a t
```

Build a map from the given bindings

**Since: 4.07**

end

Output signature of the functor `Map.Make[28.33]`.

```python
module Make :
    functor (Ord : OrderedType) -> S with type key = Ord.t
```

Functor building an implementation of the map structure given a totally ordered type.

## 28.34 Module Marshal: Marshaling of data structures.

This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml.

Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the ` Marshal.from_* ` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax:

* `( Marshal.from_channel chan : type )`. Anything can happen at run-time if the object in the file does not belong to the given type.
* 1 was the first-fit policy (since OCaml 3.11)

* 2 was the best-fit policy (since OCaml 4.10)

**Since:** 3.11

`window_size : int ;`

The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50.

**Since:** 4.03

This field is currently not available in OCaml 5: the field value is always [0].

`custom_major_ratio : int ;`

Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44.

**Since:** 4.08

`custom_minor_ratio : int ;`

Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100.

**Since:** 4.08

`custom_minor_max_size : int ;`

Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. Custom values that hold more than this many bytes are allocated on the major heap. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 70000 bytes.

**Since:** 4.08

}

The GC parameters are given as a **control** record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`.

`val stat : unit -> stat`

Return the current values of the memory management counters in a **stat** record that represents the program's total memory stats. The `heap_chunk`s, `free_blocks`, `largest_free`, and `stack_size` metrics are currently not available in OCaml 5: their returned field values are therefore 0. This function causes a full major collection.
Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the un marshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as `Printexc.to_string`, will still work as expected.

The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with ` Marshal.to_channel ` and ` Marshal.from_channel ` must be opened in binary mode, using e.g. ` open_out_bin ` or ` open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows.

`type extern_flags =`

| `No_sharing`

Don't preserve sharing

| `Closures`

Send function closures

| `Compat_32`

Ensure 32-bit compatibility

| `Compression`

Compress the output if possible

Since: 5.1

The flags to the ` Marshal.to_* ` functions below.

`val to_channel : out_channel -> 'a -> extern_flags list -> unit`

` Marshal.to_channel chan v flags ` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms.

If `flags` does not contain ` Marshal.No_sharing ` , circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to ` Marshal.to_channel ` is neither detected nor preserved, though. If `flags` contains ` Marshal.No_sharing ` , sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles.

If `flags` does not contain ` Marshal.Closures ` , marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains ` Marshal.Closures ` , functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.)
### `val quick_stat: unit -> stat`

Returns a record with the current values of the memory management counters like `stat`.

Unlike `stat`, `quick_stat` does not perform a full major collection, and hence, is much faster. However, `quick_stat` reports the counters sampled at the last minor collection or at the end of the last major collection cycle (whichever is the latest). Hence, the memory stats returned by `quick_stat` are not instantaneously accurate.

### `val counters: unit -> float * float * float`

Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`.

### `val minor_words: unit -> float`

Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code.

In native code this function does not allocate.

**Since: 4.04**

### `val get: unit -> control`

Return the current values of the GC parameters in a `control` record.

The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: their returned field values are therefore 0.

**Alert unsynchronized_access.** GC parameters are a mutable global state.

### `val set: control -> unit`

`set r` changes the GC parameters according to the `control` record `r`. The normal usage is:
```
Gc.set { (Gc.get()) with Gc.verbose = 0x00d }
```

The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: setting them therefore has no effect.

**Alert unsynchronized_access.** GC parameters are a mutable global state.

### `val minor: unit -> unit`

Trigger a minor collection.

### `val major loom: int -> int`

`major loom n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n = 0`, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0).

### `val major: unit -> unit`

Do a minor collection and finish the current major collection cycle.
The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one.

If `flags` contains ` Marshal.Compression `, the marshaled data representing value `v` is compressed before being written to channel `chan`. Decompression takes place automatically in the unmarshaling functions `input_value[27.2]`, ` Marshal.from_channel[28.34] `, ` Marshal.from_string[28.34] `, etc. For large values `v`, compression typically reduces the size of marshaled data by a factor 2 to 4, but slows down marshaling and, to a lesser extent, unmarshaling. Compression is not supported on some platforms; in this case, the ` Marshal.Compression ` flag is silently ignored and uncompressed data is written to channel `chan`.

If `flags` contains ` Marshal.Compat_32 `, marshaling fails when it encounters an integer value outside the range `[-2{^30}, 2{^30}-1]` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain ` Marshal.Compat_32 `, integer values outside the range `[-2{^30}, 2{^30}-1]` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The ` Marshal.Compat_32 ` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform.

**Before 5.1** Compression mode was not supported

**Raises** `Failure` if `chan` is not in binary mode.

val to_bytes : 'a -> extern_flags list -> bytes

` Marshal.to_bytes ` `v flags ` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for ` Marshal.to_channel [28.34]`.

**Since:** 4.02

val to_string : 'a -> extern_flags list -> string

Same as `to_bytes` but return the result as a string instead of a byte sequence.

val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int

` Marshal.to_buffer ` `buff ofs len v flags ` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised.

val from_channel : in_channel -> 'a

` Marshal.from_channel ` `chan ` reads from channel `chan` the byte representation of a structured value, as produced by one of the ` Marshal.to_* ` functions, and reconstructs and returns the corresponding value.

**Raises**
### `val full_major : unit -> unit`

Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks.

### `val compact : unit -> unit`

Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation.

### `val print_stat : out_channel -> unit`

Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument.

### `val allocated_bytes : unit -> float`

Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines.

### `val get_minor_free : unit -> int`

Return the current size of the free space inside the minor heap of this domain.

**Since: 4.03**

### `val finalise : ('a -> unit) -> 'a -> unit`

`finalise` f v registers f as a finalisation function for v. v must be heap-allocated. f will be called with v as argument at some point between the first time v becomes unreachable (including through weak pointers) and the time v is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before v becomes unreachable).

The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments.

In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads.

Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected:

* `let v = ... in Gcoppa (fun _ -> ...v...) v`

Instead you should make sure that v is not in the closure of the finalisation function by writing:

* `let f = fun x -> ... let v = ... in Gcoppa f v`
* `End_of_file` if `chan` is already at the end of the file.

* Failure if the end of the file is reached during unmarshalling itself or if `chan` is not in binary mode.

**`val from_bytes`: `bytes` -> `int` -> 'a**

` Marshal.from_bytes ` ` buff ` ` ofs ` unmarshals a structured value like ` Marshal.from_channel[28.34] ` does, except that the byte representation is not read from a channel, but taken from the byte sequence ` buff ` , starting at position ` ofs ` . The byte sequence is not mutated.

Since: 4.02

**`val from_string`: `string` -> `int` -> 'a**

Same as `from_bytes` but take a string as argument instead of a byte sequence.

**`val header_size`: `int`**

The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header.

` Marshal header_size[28.34] ` is the size, in bytes, of the header. ` Marshal.data_size[28.34] ` ` buff ` ` ofs ` is the size, in bytes, of the data part, assuming a valid header is stored in ` buff ` starting at position ` ofs ` . Finally, ` Marshal.total_size[28.34] ` ` buff ` ` ofs ` is the total size, in bytes, of the marshaled value. Both ` Marshal.data_size[28.34] ` and ` Marshal.total_size[28.34] ` raise ` Failure ` if ` buff ` , ` ofs ` does not contain a valid header.

To read the byte representation of a marshaled value into a byte sequence, the program needs to read first ` Marshal header_size[28.34] ` bytes into the sequence, then determine the length of the remainder of the representation using ` Marshal.data_size[28.34] ` , make sure the sequence is large enough to hold the remaining data, then read it, and finally call ` Marshal.from_bytes[28.34] ` to unmarshal the value.

**`val data_size`: `bytes` -> `int` -> `int`**

See ` Marshal header_size[28.34] ` .

**`val total_size`: `bytes` -> `int` -> `int`**

See ` Marshal header_size[28.34] ` .

**`val compression_supported`: `unit` -> `bool`**

Indicates whether the compressed data format is supported.

If ` Marshal.compression_supported() ` is true, compressed data is unmarshaled safely by ` input_value[27.2] ` , ` Marshal.from_channel[28.34] ` , ` Marshal.from_string[28.34] ` and related functions. Moreover, the ` Marshal.Compression ` flag is honored by the ` Marshal.to_channel[28.34] ` , ` Marshal.to_string[28.34] ` and related functions, resulting in the production of compressed data.

If ` Marshal.compression_supported() ` is false, compressed data causes ` input_value[27.2] ` , ` Marshal.from_channel[28.34] ` , ` Marshal.from_string[28.34] ` and related functions to fail
The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of `f`, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called.

`finalise` will raise `Invalid_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid_argument` for them. Values of type `'a Lazy.t` (for any `'a'`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid_argument`, but you should still avoid calling `finalise` on lazy values.

The results of calling `String.make[29.58]`, `Bytes.make[29.8]`, `Bytes.create[29.8]`, `Array.make[29.2]`, and `ref[28.2]` are guaranteed to be heap-allocated and non-constant except when the length argument is 0.

**val finalise_last : (unit -> unit) -> 'a -> unit**

same as `Gc_finalise[29.25]` except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to `Gc_finalise[29.25]` the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with `Gc_finalise[29.25]` are always called before the finalisation functions attached with `Gc_finalise_last[29.25]`.

**Since: 4.04**

**val finalise_release : unit -> unit**

A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return.

**type alarm**

An alarm is a piece of data that calls a user function at the end of major GC cycle. The following functions are provided to create and delete alarms.

**val create_alarm : (unit -> unit) -> alarm**

`create_alarm` `f` will arrange for `f` to be called at the end of major GC cycles, not caused by `f` itself, starting with the current cycle or the next one. `f` will run on the same domain that
and a `Failure` exception to be raised. Moreover, ` Marshal.to_channel [28.34] `,
` Marshal.to_string [28.34] ` and related functions ignore the ` Marshal.Compression ` flag and
produce uncompressed data.

Since: 5.1

28.35 Module MoreLabels : Extra labeled libraries.

This meta-module provides labeled versions of the `MoreLabels.Hashtbl[28.35]`, `MoreLabels.Map[28.35]` and `MoreLabels.Set[28.35]` modules.

This module is intended to be used through `open MoreLabels` which replaces `MoreLabels.Hashtbl[28.35]`, `MoreLabels.Map[28.35]`, and `MoreLabels.Set[28.35]` with their labeled counterparts.

For example:

open MoreLabels

`Hashtbl.iter ~f:(fun ~key ~data -> g key data) table`

module Hashtbl :

sig

Hash tables and hash functions.

Hash tables are hashed association tables, with in-place modification. Because most op-
erations on a hash table modify their input, they're more commonly used in imperative
code. The lookup of the value associated with a key (see `MoreLabels.Hashtbl.find[28.35]`,
`MoreLabels.Hashtbl.find_opt[28.35]`) is normally very fast, often faster than the equivalent
lookup in `MoreLabels.Map[28.35]`.

The functors `MoreLabels.Hashtbl.Make[28.35]` and `MoreLabels.Hashtbl.MakeSeeded[28.35]` can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key.

**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup.

The polymorphic `MoreLabels.Hashtbl.t[28.35]` hash table is useful in simpler cases or in
interactive environments. It uses the polymorphic `MoreLabels.Hashtbl.hash[28.35]` function
defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic
equality (`=`).

See the examples section[28.44].

Unsynchronized accesses
created the alarm, until the domain exits or `delete_alarm` is called. A value of type `alarm` is returned that you can use to call `delete_alarm`.

It is not guaranteed that the Gc alarm runs at the end of every major GC cycle, but it is guaranteed that it will run eventually.

As an example, here is a crude way to interrupt a function if the memory consumption of the program exceeds a given limit in MB, suitable for use in the toplevel:

```hkl
let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a =
let limit_memory () =
  let mem = Gc.(quick_stat()).heap_words in
  if mem / (1024 * 1024) > limit / (Sys.word_size / 8) then
    raise Out_of_memory
  in
let alarm = Gc.create_alarm limit_memory in
Fun.protect f ~finally:(fun () -> Gc.delete_alarm alarm ; Gc.compact())
```

**val delete_alarm : alarm -> unit**

`delete_alarm` a will stop the calls to the function associated to a. Calling `delete_alarm` a again has no effect.

**val eventlog_pause : unit -> unit**

*Deprecated.* Use `Runtime_events_pause` instead.

**val eventlog : unit -> unit**

*Deprecated.* Use `Runtime_events resume` instead.

**module Memprof :**

```
sig
```

```
type t
```

the type of a profile

```
type allocation_source =
```

```
| Normal
| Marshal
| Custom
| Map_file
```

```
val string_of_allocation_source : allocation_source -> string
```

```
type allocation = private
```

```
{ n Samples : int ;
```

The number of samples in this block (≥ 1).

```
size : int ;
```
Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a `Mutex.t[28.36]`).

## Generic interface

```hkl
type ('a, 'b) t = ('a, 'b) Hashtbl.t
```

The type of hash tables from type `'a` to type `'b`.

```hkl
val create : ?random:bool -> int -> ('a, 'b) t
```

`Hashtbl.create` n creates a new, empty hash table, with initial size n. For best results, n should be on the order of the expected number of elements that will be in the table. The table grows as needed, so n is just an initial guess.

The optional `~random` parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of `Hashtbl.create` or deterministic over all executions.

A hash table that is created with `~random` set to `false` uses a fixed hash function (`MoreLabels.Hashtbl.hash[28.35]`) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.

A hash table that is created with `~random` set to `true` uses the seeded hash function `MoreLabels.Hashtbl.seeded_hash[28.35]` with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among $2^{30}$ different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using `MoreLabels.Hashtbl.fold[28.35]` or `MoreLabels.Hashtbl.iter[28.35]` is no longer deterministic: elements are enumerated in different orders at different runs of the program.

If no `~random` parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling `MoreLabels.Hashtbl.randomize[28.35]` or by setting the R flag in the `OCAMLRUNPARAM` environment variable.

**Before 4.00** the `~random` parameter was not present and all hash tables were created in non-randomized mode.

```hkl
val clear : ('a, 'b) t -> unit
```

Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size.

```hkl
val reset : ('a, 'b) t -> unit
```
The size of the block, in words, excluding the header.

source : `allocation_source`;

The cause of the allocation.

callstack : `Printexc/raw_backtrace`;

The callstack for the allocation.

}

The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation.

```fortran
type ('minor', 'major') tracker =
{
    alloc_minor : allocation -> 'minor' option ;
    alloc_major : allocation -> 'major' option ;
    promote : 'minor' -> 'major' option ;
    dealloc_minor : 'minor' -> unit ;
    dealloc_major : 'major' -> unit ;
}
```

A ('minor', 'major') tracker describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: 'minor' is the type of metadata to keep for minor blocks, and 'major' the type of metadata for major blocks.

The member functions in a tracker are called callbacks.

If an allocation or promotion callback raises an exception or returns `None`, memprof stops tracking the corresponding block.

`val null Tracker : ('minor', 'major') tracker`

Default callbacks simply return `None` or `()`

```fortran
val start :
sampling_rate:float ->
?callstack_size:int -> ('minor', 'major') tracker -> t
```

Start a profile with the given parameters. Raises an exception if a profile is already sampling in the current domain.

Sampling begins immediately. The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower. $0.0 \le \text{sampling\_rate} \le 1.0$.

The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max\_int`.

The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap.
Empty a hash table and shrink the size of the bucket table to its initial size.

**Since: 4.00**

```hkl
val copy : ('a, 'b) t -> ('a, 'b) t
```

Return a copy of the given hashtable.

```hkl
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
```

`Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`.

**Warning:** Previous bindings for `key` are not removed, but simply hidden. That is, after performing `MoreLabels.Hashtbl.remove[28.35] tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.)

If you desire the classic behavior of replacing elements, see `MoreLabels.Hashtbl.replace[28.35]`.

```hkl
val find : ('a, 'b) t -> 'a -> 'b
```

`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists.

```hkl
val find_opt : ('a, 'b) t -> 'a -> 'b option
```

`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists.

**Since: 4.05**

```hkl
val find_all : ('a, 'b) t -> 'a -> 'b list
```

`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.

```hkl
val mem : ('a, 'b) t -> 'a -> bool
```

`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`.

```hkl
val remove : ('a, 'b) t -> 'a -> unit
```

`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`.

```hkl
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
```

`Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to `MoreLabels.Hashtbl.remove[28.35] tbl key` followed by `MoreLabels.Hashtbl.add[28.35] tbl key data`.

```hkl
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
```
Sampling and running callbacks are temporarily disabled on the current thread when
calling a callback, so callbacks do not need to be re-entrant if the program is
single-threaded and single-domain. However, if threads or multiple domains are used, it
is possible that several callbacks will run in parallel. In this case, callback functions
must be re-entrant.

Note that a callback may be postponed slightly after the actual event. The callstack
passed to an allocation callback always accurately reflects the allocation, but the
program state may have evolved between the allocation and the call to the callback.

If a new thread or domain is created when the current domain is sampling for a profile,
the child thread or domain joins that profile (using the same `sampling_rate`, `callstack_size`, and `tracker` callbacks).

An allocation callback is always run by the thread which allocated the block. If the
thread exits or the profile is stopped before the callback is called, the allocation callback
is not called and the block is not tracked.

Each subsequent callback is generally run by the domain which allocated the block. If
the domain terminates or the profile is stopped before the callback is called, the callback
may be run by a different domain.

Different domains may sample for different profiles simultaneously.

### `val stop : unit -> unit`

Stop sampling for the current profile. Fails if no profile is sampling in the current
domain. Stops sampling in all threads and domains sharing the profile.

Promotion and deallocation callbacks from a profile may run after `stop` is called, until `discard` is applied to the profile.

A profile is implicitly stopped (but not discarded) if all domains and threads sampling
for it are terminated.

### `val discard : t -> unit`

Discards all profiling state for a stopped profile, which prevents any more callbacks for it.

Raises an exception if called on a profile which has not been stopped.

## end

`Memprof` is a profiling engine which randomly samples allocated memory words. Every
allocated word has a probability of being sampled equal to a configurable sampling rate.
Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback
as soon as it is allocated, promoted or deallocated.

Since blocks are composed of several words, a block can potentially be sampled several times.
If a block is sampled several times, then each of the callbacks is called once for each event of
this block: the multiplicity is given in the `n Samples` field of the `allocation` structure.

This engine makes it possible to implement a low-overhead memory profiler as an OCaml
library.

Note: this API is EXPERIMENTAL. It may change without prior notice.
`Hashtbl.iter` ~f tbl applies f to all bindings in table tbl. f receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to f.

The order in which the bindings are passed to f is unspecified. However, if the table contains several bindings for the same key, they are passed to f in reverse order of introduction, that is, the most recent binding is passed first.

If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.

The behavior is not specified if the hash table is modified by f during the iteration.

### `val filter_map_inplace` :

`f:(key:'a -> data:'b -> 'b option) -> ('a, 'b) t -> unit`

`Hashtbl.filter_map_inplace` ~f tbl applies f to all bindings in table tbl and update each binding depending on the result of f. If f returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`.

Other comments for `MoreLabels.Hasttbl.iter` [28.35] apply as well.

**Since: 4.03**

### `val fold` :

`f:(key:'a -> data:'b -> 'acc -> 'acc) -> ('a, 'b) t -> init:'acc -> 'acc`

`Hashtbl.fold` ~f tbl ~init computes (`f kN dN ...` (`f k1 d1 init`)...), where `k1 ... kN` are the keys of all bindings in tbl, and `d1 ... dN` are the associated values. Each binding is presented exactly once to f.

The order in which the bindings are passed to f is unspecified. However, if the table contains several bindings for the same key, they are passed to f in reverse order of introduction, that is, the most recent binding is passed first.

If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.

The behavior is not specified if the hash table is modified by f during the iteration.

### `val length` : ('a, 'b) t -> int

`Hashtbl.length` tbl returns the number of bindings in tbl. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument.

### `val randomize` : unit -> unit
```hkl
type suspended_collection_work
```

```hkl
val ramp_up : (unit -> 'a) -> 'a * suspended_collection_work
```

In general, the OCaml GC assumes that the program runs in a "steady state" where peak memory usage remains constant: for each newly allocated work, it assumes that one work has become unreachable and will try to collect it during the next GC slice.

This assumption is incorrect at the points during program execution where the live memory increases instead of remaining stable: the steady-state assumption will make the GC work harder at no benefit as it will not find more memory to collect.

`ramp_up f` puts the current domain in a "ramp-up" phase for the duration of the evaluation of `f ()`, letting the GC know that the steady-state assumption does not hold; it should be used when you know that the live memory of the program will increase significantly.

During a ramp-up phase, the GC will not try to work harder for new allocations: the corresponding collection work is "suspended". The total amount of suspended collection work is returned by `ramp_up` along with the result of the function.

If the user discards this suspended work (by doing nothing with it), the GC will never accelerate to recover the corresponding amount of memory. This is appropriate if the ramp-up work allocates long-lived memory that remains live until the end of the program execution.

If the user knows that at a certain point in the program the live memory consumption has been reduced by the corresponding amount – typically, because the memory allocated during `ramp_up` has become unused – then they should call `Gc.ramp_down[29.25]` below to have the GC "resume" this collection work.

If `f ()` raises an exception, the ramp-up phase terminates, the collection work that was suspended is resumed, and the exception is re-raised.

If `f ()` performs an effect, the effect is not handled and an `Effect.Unhandled` exception is thrown instead.

```hkl
val ramp_down : suspended_collection_work -> unit
```

Notify the GC about some amount of collection work that was suspended during a ramp-up phase, to be resumed now.

## 29.26 Module Hashtbl: Hash tables and hash functions.

Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see `Hashtbl.find[29.26]`, `Hashtbl.find_opt[29.26]`) is normally very fast, often faster than the equivalent lookup in `Map[29.35]`.

The functors `Hashtbl.Make[29.26]` and `Hashtbl.MakeSeeded[29.26]` can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key.

**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup.
After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: `MoreLabels.Hashtbl.create[28.35]` returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the R parameter in the `OCAMLRUNPARAM` environment variable.

It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in `MoreLabels.Hashtbl.create[28.35]` call `Hashtbl.randomize()` at initialization time before any domains are created.

Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of `MoreLabels.Hashtbl.create[28.35]`. This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`.

**Since: 4.00**

`val is_randomized: unit -> bool`

Return `true` if the tables are currently created in randomized mode by default, `false` otherwise.

**Since: 4.03**

`val rebuild: ?random:bool -> ('a', 'b') t -> ('a', 'b') t`

Return a copy of the given `hashtable`. Unlike `MoreLabels.Hashtbl.copy[28.35]`, `MoreLabels.Hashtbl.rebuild[28.35]` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is `true`, or if the default is to create randomized hash tables; see `MoreLabels.Hashtbl.create[28.35]` for more information.

`MoreLabels.Hashtbl.rebuild[28.35]` can safely be used to import a hash table built by an old version of the `MoreLabels.Hashtbl[28.35]` module, then marshaled to persistent storage. After unmarshaling, apply `MoreLabels.Hashtbl.rebuild[28.35]` to produce a hash table for the current version of the `MoreLabels.Hashtbl[28.35]` module.

**Since: 4.12**

```hkl
type statistics = Hashtbl.statistics =
{
    num bindings: int;
```

Number of bindings present in the table. Same value as returned by
`MoreLabels.Hashtbl.length[28.35]`.

`num buckets: int;`

Number of buckets in the table.

`max bucket length: int;`

Maximal number of bindings per bucket.

`bucket_histogram: int array;`
The polymorphic `Hashtbl.t[29.26]` hash table is useful in simpler cases or in interactive environments. It uses the polymorphic `Hashtbl.hash[29.26]` function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality (`=`).

See the examples section [29.48].

**Alert unsynchronized_access.** Unsynchronized accesses to hash tables are a programming error.

## Unsynchronized accesses

Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a `Mutex.t[29.38]`).

## Generic interface

### type (!'a, !'b) t

The type of hash tables from type `'a` to type `'b`.

### val create : ?random:bool -> int -> ('a, 'b) t

`Hashtbl.create` `n` creates a new, empty hash table, with initial size greater or equal to the suggested size `n`. For best results, `n` should be on the order of the expected number of elements that will be in the table. The table grows as needed, so `n` is just an initial guess. If `n` is very small or negative then it is disregarded and a small default size is used.

The optional `~random` parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of `Hashtbl.create` or deterministic over all executions.

A hash table that is created with `~random` set to `false` uses a fixed hash function (`Hashtbl.hash[29.26]`) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down.

A hash table that is created with `~random` set to `true` uses the seeded hash function `Hashtbl.seeded_hash[29.26]` with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among $2^{30}$ different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using `Hashtbl.fold[29.26]` or `Hashtbl.iter[29.26]` is no longer deterministic: elements are enumerated in different orders at different runs of the program.

If no `~random` parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling `Hashtbl.randomize[29.26]` or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable.

**Before 4.00** the `~random` parameter was not present and all hash tables were created in non-randomized mode.

### val clear : ('a, 'b) t -> unit
Histogram of bucket sizes. This array histo has length max bucket length + 1. The value of histo.(i) is the number of buckets whose size is i.

}

Since: 4.00

val stats: ('a, 'b) t -> statistics

Hashtbl.stats tbl returns statistics about the table tbl: number of buckets, size of the biggest bucket, distribution of buckets by size.

Since: 4.00

## Hash tables and Sequences

val to_seq: ('a, 'b) t -> ('a * 'b) Seq.t

Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. The behavior is not specified if the hash table is modified during the iteration.

Since: 4.07

val to_seq_keys: ('a, 'b) t -> 'a Seq.t

Same as Seq.map fst (to_seq m)

Since: 4.07

val to_seq_values: ('a, 'b) t -> 'b Seq.t

Same as Seq.map snd (to_seq m)

Since: 4.07

val add_seq: ('a, 'b) t -> ('a * 'b) Seq.t -> unit

Add the given bindings to the table, using MoreLabels.Hashtbl.add[28.35]

Since: 4.07

val replace_seq: ('a, 'b) t -> ('a * 'b) Seq.t -> unit

Add the given bindings to the table, using MoreLabels.Hashtbl.replace[28.35]

Since: 4.07

val of_seq: ('a * 'b) Seq.t -> ('a, 'b) t

Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using MoreLabels.Hashtbl.replace_seq[28.35], which means that if two pairs have the same key, only the latest one will appear in the table.

Since: 4.07
Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size.

**val reset : ('a, 'b) t -> unit**

Empty a hash table and shrink the size of the bucket table to its initial size.

**Since: 4.00**

**val copy : ('a, 'b) t -> ('a, 'b) t**

Return a copy of the given hashtable.

**val add : ('a, 'b) t -> 'a -> 'b -> unit**

`Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`.

**Warning:** Previous bindings for `key` are not removed, but simply hidden. That is, after performing `Hashtbl.remove[29.26] tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.)

If you desire the classic behavior of replacing elements, see `Hashtbl.replace[29.26]`.

**val find : ('a, 'b) t -> 'a -> 'b**

`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists.

**val find_opt : ('a, 'b) t -> 'a -> 'b option**

`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists.

**Since: 4.05**

**val find_all : ('a, 'b) t -> 'a -> 'b list**

`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table.

**val mem : ('a, 'b) t -> 'a -> bool**

`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`.

**val remove : ('a, 'b) t -> 'a -> unit**

`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`.

**val replace : ('a, 'b) t -> 'a -> 'b -> unit**

`Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to `Hashtbl.remove[29.26] tbl key` followed by `Hashtbl.add[29.26] tbl key data`.
## Functorial interface

The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.

For instance, one might want to specialize a table for integer keys:

```python
module IntHash =
    struct
        type t = int
        let equal i j = i=j
        let hash i = i land max_int
    end

module IntHashtbl = Hashtbl.Make(IntHash)

let h = IntHashtbl.create 17 in
    IntHashtbl.add h 12 "hello"
```

This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a'`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`.

Note that the new type `'a IntHashtbl.t` is not compatible with the type (`'a, 'b`) `Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`.

```python
module type HashedType =
    sig
        type t
        The type of the hashtable keys.
```

```python
val equal : t -> t -> bool
    The equality predicate used to compare keys.
```

```python
val hash : t -> int
    A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include

* `((=), MoreLabels.Hashtbl.HashedType.hash[28.35])` for comparing objects by structure (provided objects do not contain floats)

* `((fun x y -> compare x y = 0), MoreLabels.Hashtbl.HashedType.hash[28.35])` for comparing objects by structure and handling `nan[27.2]` correctly

* `((==), MoreLabels.Hashtbl.HashedType.hash[28.35])` for comparing objects by physical equality (e.g. for mutable or cyclic objects).
```hcl
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
```

`Hashtbl.iter` `f` `tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`.

The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first.

If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.

The behavior is not specified if the hash table is modified by `f` during the iteration.

```hcl
val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
```

`Hashtbl.filter_map_inplace` `f` `tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`.

Other comments for `Hashtbl.iter` [29.26] apply as well.

**Since: 4.03**

```hcl
val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc
```

`Hashtbl.fold` `f` `tbl` `init` computes (`f kN dN ...` (`f k1 d1 init`)...), where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`.

The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first.

If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random.

The behavior is not specified if the hash table is modified by `f` during the iteration.

```hcl
val length : ('a, 'b) t -> int
```

`Hashtbl.length` `tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument.

```hcl
val randomize : unit -> unit
```

After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: `Hashtbl.create` [29.26] returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable.
end

The input signature of the functor `MoreLabels.Hashtbl.Make[28.35]`.

module type S =

sig

type key

type !'a t

val create : int -> 'a t

val clear : 'a t -> unit

val reset : 'a t -> unit

Since: 4.00

val copy : 'a t -> 'a t

val add : 'a t -> key:key -> data:'a -> unit

val remove : 'a t -> key -> unit

val find : 'a t -> key -> 'a

val find_opt : 'a t -> key -> 'a option

Since: 4.05

val find_all : 'a t -> key -> 'a list

val replace : 'a t -> key:key -> data:'a -> unit

val mem : 'a t -> key -> bool

val iter : f:(key:key -> data:'a -> unit) ->
'a t -> unit

val filter_map_inplace :

f:(key:key -> data:'a -> 'a option) ->
'a t -> unit

Since: 4.03

val fold :

f:(key:key -> data:'a -> 'acc -> 'acc) ->
'a t -> init:'acc -> 'acc

val length : 'a t -> int

val stats : 'a t -> MoreLabels.Hashtbl.statistics

Since: 4.00

val to_seq : 'a t -> (key * 'a) Seq.t

Since: 4.07

val to_seq_keys : 'a t -> key Seq.t

Since: 4.07
It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in `Hashtbl.create[29.26]` call `Hashtbl.randomize()` at initialization time before any domains are created.

Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of `Hashtbl.create[29.26]`. This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`.

**Since: 4.00**

`val is_randomized: unit -> bool`

Return `true` if the tables are currently created in randomized mode by default, `false` otherwise.

**Since: 4.03**

`val rebuild: ?random:bool -> ('a, 'b) t -> ('a, 'b) t`

Return a copy of the given hashtable. Unlike `Hashtbl.copy[29.26]`, `Hashtbl.rebuild[29.26]` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see `Hashtbl.create[29.26]` for more information.

`Hashtbl.rebuild[29.26]` can safely be used to import a hash table built by an old version of the `Hashtbl[29.26]` module, then marshaled to persistent storage. After unmarshaling, apply `Hashtbl.rebuild[29.26]` to produce a hash table for the current version of the `Hashtbl[29.26]` module.

**Since: 4.12**

type statistics =
{
  num bindings: int;
  Number of bindings present in the table. Same value as returned by
  Hashtbl.length[29.26].

numiranments : int ;
  Number of buckets in the table.

max bucket length : int ;
  Maximal number of bindings per bucket.

bucket_histogram : int array ;
  Histogram of bucket sizes. This array histo has length max bucket length + 1. The
  value of histo.(i) is the number of buckets whose size is i.

}

**Since: 4.00**

`val stats: ('a, 'b) t -> statistics`

`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size.

**Since: 4.00**
```kotlin
val to_seq_values : 'a t -> 'a Seq.t
    Since: 4.07

val add_seq : 'a t ->
    (key * 'a) Seq.t -> unit
    Since: 4.07

val replace_seq : 'a t ->
    (key * 'a) Seq.t -> unit
    Since: 4.07

val of_seq : (key * 'a) Seq.t -> 'a t
    Since: 4.07

end
```

The output signature of the functor `MoreLabels.Hashtbl.Make[28.35]`.

```kotlin
module Make :
functor (H : HashedType) -> S with type key = H.t and type 'a t = 'a
Hashtbl.Make(H).t
```

Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables.

```kotlin
module type SeededHashedType =
sig
```

```kotlin
type t
```

The type of the hashtable keys.

```kotlin
val equal : t ->
    t -> bool
```

The equality predicate used to compare keys.

```kotlin
val seeded_hash : int -> t -> int
```

A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function `MoreLabels.Hashtbl.seeded_hash[28.35]` below.
## Hash tables and Sequences

val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t

Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first.

The behavior is not specified if the hash table is modified during the iteration.

**Since:** 4.07

val to_seq_keys : ('a, 'b) t -> 'a Seq.t

Same as `Seq.map fst (to_seq m)`

**Since:** 4.07

val to_seq_values : ('a, 'b) t -> 'b Seq.t

Same as `Seq.map snd (to_seq m)`

**Since:** 4.07

val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit

Add the given bindings to the table, using `Hashtbl.add[29.26]`

**Since:** 4.07

val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit

Add the given bindings to the table, using `Hashtbl.replace[29.26]`

**Since:** 4.07

val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t

Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using `Hashtbl.replace_seq[29.26]`, which means that if two pairs have the same key, only the latest one will appear in the table.

**Since:** 4.07

## Fundorialal interface

The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins.

For instance, one might want to specialize a table for integer keys:

```python
module IntHash =
    struct
        type t = int
        let equal i j = i=j
```
```pascal
let hash i = i land max_int
end

module IntHashtbl = Hashtbl.Make(IntHash)

let h = IntHashtbl.create 17 in
IntHashtbl.add h 12 "hello"
```

This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a'`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`.

Note that the new type `'a IntHashtbl.t` is not compatible with the type (`'a, 'b`) `Hashtbl.t` of the generic interface. For example, `Hashtbl.length` `h` would not type-check, you must use `IntHashtbl.length`.

```pascal
module type HashedType =
sig
    type t
```

The type of the hashtable keys.

```pascal
    val equal : t -> t -> bool
```

The equality predicate used to compare keys.

```pascal
    val hash : t -> int
```

A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include

* `((=), Hashtbl.HashedType.hash[29.26])` for comparing objects by structure (provided objects do not contain floats)

* `((fun x y -> compare x y = 0), Hashtbl.HashedType.hash[29.26])` for comparing objects by structure and handling `nan[28.2]` correctly

* `((==), Hashtbl.HashedType.hash[29.26])` for comparing objects by physical equality (e.g. for mutable or cyclic objects).

```pascal
end
```

The input signature of the functor `Hashtbl.Make[29.26]`.

```pascal
module type S =
sig
    type key
    type !'a t
    val create : int -> 'a t
    val clear : 'a t -> unit
    val reset : 'a t -> unit
```
```rust
val to_seq_keys: 'a t ->
key Seq.t
    Since: 4.07

val to_seq_values: 'a t -> 'a Seq.t
    Since: 4.07

val add_seq: 'a t ->
(key * 'a) Seq.t -> unit
    Since: 4.07

val replace_seq: 'a t ->
(key * 'a) Seq.t -> unit
    Since: 4.07

val of_seq: (key * 'a) Seq.t ->
'a t
    Since: 4.07

end
```

The output signature of the functor `MoreLabels.Hashtbl.MakeSeeded[28.35]`.

Since: 4.00

```rust
module MakeSeeded :
functor (H : SeededHashedType) -> SeededS with type key = H.t and type 'a t
= 'a Hashtbl.MakeSeeded(H) .t
```

Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see `MoreLabels.Hashtbl.randomize[28.35]`).

Since: 4.00

## The polymorphic hash functions

```rust
val hash: 'a -> int
```

`Hashtbl.hash` `x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib comparisons` `x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures.
Since: 4.00

val copy : 'a t -> 'a t
val add : 'a t -> key -> 'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option

Since: 4.05

val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key -> 'a -> unit
val mem : 'a t -> key -> bool
val iter : (key -> 'a -> unit) -> 'a t -> unit
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit

Since: 4.03

val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc
val length : 'a t -> int
val stats : 'a t -> Hashtbl.statistics

Since: 4.00

val to_seq : 'a t -> (key * 'a) Seq.t

Since: 4.07

val to_seq_keys : 'a t -> key Seq.t

Since: 4.07

val to_seq_values : 'a t -> 'a Seq.t

Since: 4.07

val add_seq : 'a t -> (key * 'a) Seq.t -> unit

Since: 4.07

val replace_seq : 'a t -> (key * 'a) Seq.t -> unit

Since: 4.07

val of_seq : (key * 'a) Seq.t -> 'a t

Since: 4.07
```kotlin
val seeded_hash : int -> 'a -> int
```

A variant of `MoreLabels.Hashtbl.hash` [28.35] that is further parameterized by an integer seed.

**Since: 4.00**

```kotlin
val hash_param : int -> int -> 'a -> int
```

`Hashtbl.hash_param` meaningful `total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, `MoreLabels.Hashtbl.hash` [28.35] and `MoreLabels.Hashtbl.seeded_hash` [28.35] take `meaningful = 10` and `total = 100`.

```kotlin
val seeded_hash_param : int -> int -> int -> 'a -> int
```

A variant of `MoreLabels.Hashtbl.hash_param` [28.35] that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`.

**Since: 4.00**

## Examples

### Basic Example

```kotlin
(* 0...99 *)
let seq = Seq.ints 0 |> Seq.take 100

(* build from Seq.t *)
# let tbl =
    seq
  |> Seq.map (fun x -> x, string_of_int x)
  |> Hashtbl.of_seq
val tbl : (int, string) Hashtbl.t = <abstr>

# Hashtbl.length tbl
- : int = 100
```
end

The output signature of the functor `Hashtbl.Make[29.26]`.

module Make :

functor (H : HashedType) -> S with type key = H.t

Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables.

module type SeededHashedType =

sig

type t

The type of the hashtable keys.

val equal : t -> t -> bool

The equality predicate used to compare keys.

val seeded_hash : int -> t -> int

A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function `Hashtbl.seeded_hash[29.26]` below.

end

The input signature of the functor `Hashtbl.MakeSeeded[29.26]`.

Since: 4.00

module type SeededS =

sig

type key

type !'a t

val create : ?random:bool -> int -> 'a t

val clear : 'a t -> unit

val reset : 'a t -> unit

val copy : 'a t -> 'a t

val add : 'a t -> key -> 'a -> unit

val remove : 'a t -> key -> unit

val find : 'a t -> key -> 'a

val find_opt : 'a t -> key -> 'a option
```go
# Hashtbl.find_opt tbl 32
- : string option = Some "32"

# Hashtbl.find_opt tbl 166
- : string option = None

# Hashtbl.replace tbl 166 "one six six"
- : unit = ()

# Hashtbl.find_opt tbl 166
- : string option = Some "one six six"

# Hashtbl.length tbl
- : int = 101
```

## Counting Elements

Given a sequence of elements (here, a `Seq.t[28.48]`), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences.

Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`.

```go
# module Char_tbl = Hashtbl.Make(struct
  type t = char
  let equal = Char equal
  let hash = Hashtbl.hash
end)

(* count distinct occurrences of chars in [seq] *)
# let count_chars (seq : char Seq.t) : _ list =
  let counts = Char_tbl.create 16 in
  Seq.iter
  (fun c ->
    let count_c =
      Char_tbl.find_opt counts c
    |> Option.value ~default:0
    in
      Char_tbl.replace counts c (count_c + 1))
  seq;
(* turn into a list *)
Char_tbl.fold (fun c n 1 -> (c,n) :: 1) counts []
```
Since: 4.05

val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key -> 'a -> unit
val mem : 'a t -> key -> bool
val iter : (key -> 'a -> unit) -> 'a t -> unit
val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit

Since: 4.03

val fold : (key -> 'a -> 'acc -> 'acc) ->
'a t -> 'acc -> 'acc
val length : 'a t -> int
val stats : 'a t -> Hashtbl.statistics
val to_seq : 'a t -> (key * 'a) Seq.t

Since: 4.07

val to_seq_keys : 'a t -> key Seq.t

Since: 4.07

val to_seq_values : 'a t -> 'a Seq.t

Since: 4.07

val add_seq : 'a t -> (key * 'a) Seq.t -> unit

Since: 4.07

val replace_seq : 'a t -> (key * 'a) Seq.t -> unit

Since: 4.07

val of_seq : (key * 'a) Seq.t -> 'a t

Since: 4.07

end

The output signature of the functor Hashtbl.MakeSeeded[29.26].

Since: 4.00

module MakeSeeded :
functor (H : SeededHashedType) -> SeededS with type key = H.t
|> List.sort (fun (c1,_) (c2,_) -> Char compares c1 c2)
val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = <fun>

(* basic seq from a string *)
# let seq = String.to_seq "hello world, and all the camels in it!"
val seq : char Seq.t = <fun>

# count_chars seq
- : (Char.t * int) list =
  [(', 7); ('!', 1); (' ', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3);
   ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1);
   ('s', 1); ('t', 2); ('w', 1)]

(* "abcabcabc..." *)
# let seq2 =
Seq Provided (String.to_seq "abc") |> Seq.take 31
val seq2 : char Seq.t = <fun>

# String.of_seq seq2
- : String.t = "abcabcabcabcabcabcabcabcabca"

# count_chars seq2
- : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)]

end

module Map :
sig

Association tables over ordered types.

This module implements applicative association tables, also known as finite maps or dictionaries,
given a total ordering function over the keys. All operations over maps are purely applicative
(no side-effects). The implementation uses balanced binary trees, and therefore searching and
insertion take time logarithmic in the size of the map.

For instance:

module IntPairs =
  struct
    type t = int * int
    let compare (x0,y0) (x1,y1) =
      match Stdlib compare x0 x1 with
        0 -> Stdlib compare y0 y1
      | c -> c
  end
Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see `Hashtbl.randomize[29.26]`).

**Since:** 4.00

## The polymorphic hash functions

`val hash : 'a -> int`

`Hashtbl.hash` `x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib compares x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures.

`val seeded_hash : int -> 'a -> int`

A variant of `Hashtbl.hash[29.26]` that is further parameterized by an integer seed.

**Since:** 4.00

`val hash_param : int -> int -> 'a -> int`

`Hashtbl.hash_param` meaningful `total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, `Hashtbl.hash[29.26]` and `Hashtbl.seeded_hash[29.26]` take `meaningful = 10` and `total = 100`.

`val seeded_hash_param : int -> int -> int -> 'a -> int`

A variant of `Hashtbl.hash_param[29.26]` that is further parameterized by an integer seed.

**Usage:** `Hashtbl.seeded_hash_param meaningful total seed x`.

**Since:** 4.00

## Examples

### Basic Example
```kotlin
module PairsMap = Map.Make(IntPairs)

let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
```

This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`.

```kotlin
module type OrderedType =
```

```kotlin
sig

type t

The type of the map keys.

val compare : t -> t -> int
```

A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function `compare[27.2]`.

```kotlin
end

Input signature of the functor MoreLabels.Map.Make[28.35].

module type S =
```

```kotlin
sig

Maps
```

```kotlin
type key

The type of the map keys.

type !+'a t

The type of maps from type `key` to type `'a`.

val empty : 'a t

The empty map.

val add : key:key ->

data:'a -> 'a t -> 'a t
```

`add ~key ~data` `m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears.

**Before 4.03** Physical equality was not ensured.
```python
(* 0...99 *)
let seq = Seq.ints 0 |> Seq.take 100

(* build from Seq.t *)
# let tbl =
    seq
    |> Seq.map (fun x -> x, string_of_int x)
    |> Hashtbl.of_seq
val tbl : (int, string) Hashtbl.t = <abstr>

# Hashtbl.length tbl
- : int = 100

# Hashtbl.find_opt tbl 32
- : string option = Some "32"

# Hashtbl.find_opt tbl 166
- : string option = None

# Hashtbl.replace tbl 166 "one six six"
- : unit = ()

# Hashtbl.find_opt tbl 166
- : string option = Some "one six six"

# Hashtbl.length tbl
- : int = 101
```

## Counting Elements

Given a sequence of elements (here, a `Seq.t[29.53]`), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences.

Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`.

```python
# module Char_tbl = Hashtbl.Make(struct
    type t = char
    let equal = Char equal
    let hash = Hashtbl.hash
end)

(* count distinct occurrences of chars in [seq] *)
# let count_chars (seq : char Seq.t) : _ list =
```
```hkl
val add_to_list : key:key ->
  data:'a -> 'a list t -> 'a list t
```

```hkl
add_to_list ~key ~data m is m with key mapped to l such that l is data ::
  Map.find key m if key was bound in m and [v] otherwise.
```

**Since: 5.1**

```hkl
val update : key:key ->
  f:('a option -> 'a option) -> 'a t -> 'a t
```

```hkl
update ~key ~f m returns a map containing the same bindings as m, except for the
  binding of key. Depending on the value of y where y is f (find_opt key m), the
  binding of key is added, removed or updated. If y is None, the binding is removed if
  it exists; otherwise, if y is Some z then key is associated to z in the resulting map.
  If key was already bound in m to a value that is physically equal to z, m is returned
  unchanged (the result of the function is then physically equal to m).
```

**Since: 4.06**

```hkl
val singleton : key -> 'a -> 'a t
```

```hkl
singleton x y returns the one-element map that contains a binding y for x.
```

**Since: 3.12**

```hkl
val remove : key -> 'a t -> 'a t
```

```hkl
remove x m returns a map containing the same bindings as m, except for x which is
  unbound in the returned map. If x was not in m, m is returned unchanged (the result
  of the function is then physically equal to m).
```

**Before 4.03** Physical equality was not ensured.

```hkl
val merge :
  f:(key -> 'a option -> 'b option -> 'c option) ->
  'a t -> 'b t -> 'c t
```

```hkl
merge ~f m1 m2 computes a map whose keys are a subset of the keys of m1 and of
  m2. The presence of each such binding, and the corresponding value, is determined
  with the function f. In terms of the find_opt operation, we have find_opt x
  (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2) for any key x,
  provided that f x None None = None.
```

**Since: 3.12**

```hkl
val union : f:(key -> 'a -> 'a -> 'a option) ->
  'a t -> 'a t -> 'a t
```

```hkl
union ~f m1 m2 computes a map whose keys are a subset of the keys of m1 and of
  m2. When the same binding is defined in both arguments, the function f is used to
  combine them. This is a special case of merge: union f m1 m2 is equivalent to
  merge f' m1 m2, where
  * f' _key None None = None
  * f' _key (Some v) None = Some v
  * f' _key None (Some v) = Some v
```
```kotlin
let counts = Char_tbl.create 16 in
Seq.iter
 fun c ->
     let count_c =
         Char_tbl.find_opt counts c
     |> Option.value ~default:0
     in
         Char_tbl.replace counts c (count_c + 1))
     seq;
     (* turn into a list *)
         Char_tbl.fold (fun c n l -> (c,n) :: 1) counts []
     |> List.sort (fun (c1_,_) (c2_,_) -> Char compares c1 c2)
val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = <fun>

(* basic seq from a string *)
# let seq = String.to_seq "hello world, and all the camels in it!"
val seq : char Seq.t = <fun>

# count_chars seq
- : (Char.t * int) list =
  [( ' , 7); ('! ', 1); (' ', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3);
   ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1);
   ('s', 1); ('t', 2); ('w', 1)]

(* "abcabcabc..." *)
# let seq2 =
         Seq Provided (String.to_seq "abc") |> Seq.take 31
val seq2 : char Seq.t = <fun>

# String.of_seq seq2
- : String.t = "abcabcabcabcabcabcabcabcabcabca"

# count_chars seq2
- : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)]
```

## 29.27 Module In_channel: Input channels.

This module provides functions for working with input channels.
See the example section [29.48] below.

Since: 4.14
* `f` key (Some v1) (Some v2) = `f` key v1 v2

Since: 4.03

`val cardinal : 'a t -> int`

Return the number of bindings of a map.

Since: 3.12

## Bindings

`val bindings : 'a t -> (key * 'a) list`

Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord compares`, where `Ord` is the argument given to `MoreLabels.Map.Make[28.35]`.

Since: 3.12

`val min_bind : 'a t -> key * 'a`

Return the binding with the smallest key in a given map (with respect to the `Ord compares` ordering), or raise `Not_found` if the map is empty.

Since: 3.12

`val min_bind_opt : 'a t -> (key * 'a) option`

Return the binding with the smallest key in the given map (with respect to the `Ord compares` ordering), or `None` if the map is empty.

Since: 4.05

`val max_bind : 'a t -> key * 'a`

Same as `MoreLabels.Map.S.min_bind[28.35]`, but returns the binding with the largest key in the given map.

Since: 3.12

`val max_bind_opt : 'a t -> (key * 'a) option`

Same as `MoreLabels.Map.S.min_bind_opt[28.35]`, but returns the binding with the largest key in the given map.

Since: 4.05

`val choose : 'a t -> key * 'a`

Return one binding of the given map, or raise `Not_found` if the map is empty.

Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.

Since: 3.12

`val choose_opt : 'a t -> (key * 'a) option`

Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps.

Since: 4.05
Channels

type t = in_channel

The type of input channel.

type open_flag = open_flag =

| Open_rdoonly

open for reading.

| Open_wronly

open for writing.

| Open_append

open for appending: always write at end of file.

| Open_creat

create the file if it does not exist.

| Open_trunc

empty the file if it already exists.

| Open_excl

fail if Open_creat and the file already exists.

| Open_binary

open in binary mode (no conversion).

| Open_text

open in text mode (may perform conversions).

| Open_nonblock

open in non-blocking mode.

Opening modes for In_channel.open_gen[29.27].

val stdin : t

The standard input for the process.

val open_bin : string -> t

Open the named file for reading, and return a new input channel on that file, positioned at
the beginning of the file.

val open_text : string -> t

Same as In_channel.open_bin[29.27], but the file is opened in text mode, so that newline
translation takes place during reads. On operating systems that do not distinguish between
text mode and binary mode, this function behaves like In_channel.open_bin[29.27].

val open_gen : open_flag list -> int -> string -> t
## Searching

`val find : key -> 'a t -> 'a`

`find` `x` `m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists.

`val find_opt : key -> 'a t -> 'a option`

`find_opt` `x` `m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists.

**Since:** 4.05

`val find_first : f:(key -> bool) ->`

`'a t -> key * 'a`

`find_first` ~`f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists.

For example, `find_first (fun k -> Ord compares k x >= 0) m` will return the first binding `k`, `v` of `m` where `Ord comparisons k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`.

**Since:** 4.05

`val find_first_opt : f:(key -> bool) ->`

`'a t -> (key * 'a) option`

`find_first_opt` ~`f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists.

**Since:** 4.05

`val find_last : f:(key -> bool) ->`

`'a t -> key * 'a`

`find_last` ~`f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists.

**Since:** 4.05

`val find_last_opt : f:(key -> bool) ->`

`'a t -> (key * 'a) option`

`find_last_opt` ~`f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists.

**Since:** 4.05

## Traversing

`val iter : f:(key:key -> data:'a -> unit) ->`

`'a t -> unit`
`open_gen` mode `perm` filename opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions.

`In_channel.open_text[29.27]` and `In_channel.open_bin[29.27]` are special cases of this function.

`val with_open_bin : string -> (t -> 'a) -> 'a`

`with_open_bin` `fn` `f` opens a channel `ic` on file `fn` and returns `f` `ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed.

`val with_open_text : string -> (t -> 'a) -> 'a`

Like `In_channel.with_open_bin[29.27]`, but the channel is opened in text mode (see `In_channel.open_text[29.27]`).

`val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a`

Like `In_channel.with_open_bin[29.27]`, but can specify the opening mode and file permission, in case the file must be created (see `In_channel.open_gen[29.27]`).

`val close : t -> unit`

Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except `In_channel.close[29.27]`, which does nothing when applied to an already closed channel.

`val close_noerr : t -> unit`

Same as `In_channel.close[29.27]`, but ignore all errors.

## Input

`val input_char : t -> char option`

Read one character from the given input channel. Returns `None` if there are no more characters to read.

`val input_byte : t -> int option`

Same as `In_channel.input_char[29.27]`, but return the 8-bit integer representing the character. Returns `None` if the end of file was reached.

`val input_line : t -> string option`

`input_line` `ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty.

A newline is the character `\n` unless the file is open in text mode and `Sys.win32[29.60]` is true in which case it is the sequence of characters `\r\n`.

`val really_input_string : t -> int -> string option`
`iter ~f m` applies `f` to all bindings in `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.

**val fold :**
```h
f:(key:key -> data:'a -> 'acc -> 'acc) ->
'a t -> init:'acc -> 'acc
```
**fold ~f m ~init** computes (`f kN dN ...` (`f k1 d1 init`)...), where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data.

Transforming

**val map :** `f:('a -> 'b) -> 'a t -> 'b t`

`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys.

**val mapi :** `f:(key -> 'a -> 'b) ->
'a t -> 'b t`

Same as `MoreLabels.Map.S.map[28.35]`, but the function receives as arguments both the key and the associated value for each binding of the map.

**val filter :** `f:(key -> 'a -> bool) ->
'a t -> 'a t`

`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`).

**Before 4.03** Physical equality was not ensured.

**Since:** 3.12

**val filter_map :** `f:(key -> 'a -> 'b option) ->
'a t -> 'b t`

`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding (`k`, `v`) in the input map:

* if `f k v` is `None` then `k` is not in the result,

* if `f k v` is `Some v'` then the binding (`k`, `v'`) is in the output map.

For example, the following function on maps whose values are lists

```h
filter_map
    (fun _k li -> match li with [] -> None | _:::tl -> Some tl)
    m
```
`really_input_string` `ic` `len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read.

If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input.

`val input_all : t -> string`

`input_all` `ic` reads all remaining data from `ic`.

If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input.

`val input_lines : t -> string list`

`input_lines` `ic` reads lines using `In_channel.input_line` [29.27] until the end of file is reached. It returns the list of all lines read, in the order they were read. The newline characters that terminate lines are not included in the returned strings. Empty lines produce empty strings.

**Since:** 5.1

Advanced input

`val input : t -> bytes -> int -> int -> int`

`input` `ic` `buf` `pos` `len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached.

Use `In_channel.really_input` [29.27] to read exactly `len` characters.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.

`val input_bigarray :`

```
t ->
('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout)
Bigarray Array1.t -> int -> int -> int
```

Same as `In_channel.input` [29.27], but read the data into a `bigarray`.

**Since:** 5.2

`val really_input : t -> bytes -> int -> int -> unit option`

`really_input` `ic` `buf` `pos` `len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`.

Returns `None` if the end of file is reached before `len` characters have been read.

If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
drops all bindings of m whose value is an empty list, and pops the first element of
each value that is non-empty.

Since: 4.11

val partition : f:(key -> 'a -> bool) ->
'a t -> 'a t * 'a t

partition ~f m returns a pair of maps (m1, m2), where m1 contains all the
bindings of m that satisfy the predicate f, and m2 is the map with all the bindings of
m that do not satisfy f.

Since: 3.12

val split : key ->
'a t ->
'a t * 'a option * 'a t

split x m returns a triple (l, data, r), where l is the map with all the bindings of m whose key is strictly less than x; r is the map with all the bindings of m whose key is strictly greater than x; data is None if m contains no binding for x, or Some v if m binds v to x.

Since: 3.12

Predicates and comparisons

val is_empty : 'a t -> bool

Test whether a map is empty or not.

val mem : key -> 'a t -> bool

mem x m returns true if m contains a binding for x, and false otherwise.

val equal : cmp:('a -> 'a -> bool) ->
'a t -> 'a t -> bool

equal ~cmp m1 m2 tests whether the maps m1 and m2 are equal, that is, contain
equal keys and associate them with equal data. cmp is the equality predicate used to
compare the data associated with the keys.

val compare : cmp:('a -> 'a -> int) ->
'a t -> 'a t -> int

Total ordering between maps. The first argument is a total ordering used to
compare data associated with equal keys in the two maps.

val for_all : f:(key -> 'a -> bool) -> 'a t -> bool

for_all ~f m checks if all the bindings of the map satisfy the predicate f.

Since: 3.12

val exists : f:(key -> 'a -> bool) -> 'a t -> bool

exists ~f m checks if at least one binding of the map satisfies the predicate f.

Since: 3.12
```hcl
val really_input_bigarray :
```

```hcl
t ->
('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout)
Bigarray Array1.t -> int -> int -> unit option
```

Same as `In_channel.really_input[29.27]`, but read the data into a bigarray.

Since: 5.2

```hcl
val fold_lines : ('acc -> string -> 'acc) -> 'acc -> t -> 'acc
```

`fold_lines f init ic` reads lines from `ic` using `In_channel.input_line[29.27]` until the end of file is reached, and successively passes each line to function `f` in the style of a fold. More precisely, if lines `l1, ..., lN` are read, `fold_lines f init ic` computes `f (... (f init l1) l2) ...)` `lN`. If `f` has no side effects, this is equivalent to `List.fold_left f init (In_channel.input_lines ic)`, but is more efficient since it does not construct the list of all lines read.

Since: 5.1

## Seeking

```hcl
val seek : t -> int64 -> unit
```

`seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified.

```hcl
val pos : t -> int64
```

Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `In_channel.pos[29.27]`, then going back to this position using `In_channel.seek[29.27]` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.

## Attributes

```hcl
val length : t -> int64
```

Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode.

```hcl
val set_binary_mode : t -> bool -> unit
```

`set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input.

`set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`.
Converting

val to_list : 'a t -> (key * 'a) list

to_list m is MoreLabels.Map.S.bindings[28.35] m.
Since: 5.1

val of_list : (key * 'a) list -> 'a t

of_list bs adds the bindings of bs to the empty map, in list order (if a key is
bound twice in bs the last one takes over).
Since: 5.1

val to_seq : 'a t -> (key * 'a) Seq.t
Iterate on the whole map, in ascending order of keys
Since: 4.07

val to_rev_seq : 'a t -> (key * 'a) Seq.t
Iterate on the whole map, in descending order of keys
Since: 4.12

val to_seq_from : key ->
'a t -> (key * 'a) Seq.t

to_seq_from k m iterates on a subset of the bindings of m, in ascending order of
keys, from key k or above.
Since: 4.07

val add_seq : (key * 'a) Seq.t ->
'a t -> 'a t

Add the given bindings to the map, in order.
Since: 4.07

val of_seq : (key * 'a) Seq.t -> 'a t
Build a map from the given bindings
Since: 4.07

end

Output signature of the functor MoreLabels.Map.Make[28.35].

module Make :
functor (Ord : OrderedType) -> S with type key = Ord.t and type 'a t = 'a
Map.Make(Ord).t

Functor building an implementation of the map structure given a totally ordered type.

end

module Set :
sig
This function has no effect under operating systems that do not distinguish between text
mode and binary mode.

val is_binary_mode : t -> bool
is_binary_mode ic returns whether the channel ic is in binary mode (see
In_channel.set_binary_mode[29.27]).

Since: 5.2

val isatty : t -> bool
isatty ic is true if ic refers to a terminal or console window, false otherwise.

Since: 5.1

Examples

Reading the contents of a file:

let read_file file = In_channel.open_bin file In_channel.input_all

Reading a line from stdin:

let user_input () = In_channel.input_line In_channel.stdin

29.28 Module Int : Integer values.

Integers are Sys.int_size[29.60] bits wide and use two's complement representation. All operations
are taken modulo 2<sup>Sys.int_size</sup>. They do not fail on overflow.

Since: 4.08

Integers

type t = int
The type for integer values.

val zero : int
zero is the integer 0.

val one : int
one is the integer 1.

val minus_one : int
minus_one is the integer -1.
Sets over ordered types.

This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.

The `MoreLabels.Set.Make[28.35]` functor constructs implementations for any type, given a `compare` function. For instance:

```python
module IntPairs =
    struct
        type t = int * int
        let compare (x0,y0) (x1,y1) =
            match Stdlib comparisons x0 x1 with
                0 -> Stdlib compare y0 y1
                | c -> c
        end

module PairsSet = Set.Make(IntPairs)

let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
```

This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`.

```python
module type OrderedType =
    sig
        type t
        The type of the set elements.
        val compare : t -> t -> int
        A total ordering function over the set elements. This is a two-argument function f
        such that f e1 e2 is zero if the elements e1 and e2 are equal, f e1 e2 is strictly
        negative if e1 is smaller than e2, and f e1 e2 is strictly positive if e1 is greater
        than e2. Example: a suitable ordering function is the generic structural comparison
        function compare[27.2].
    end

Input signature of the functor MoreLabels.Set.Make[28.35].

module type S =
    sig
```
val neg : int -> int

neg x is ~-x.

val add : int -> int -> int

add x y is the addition x + y.

val sub : int -> int -> int

sub x y is the subtraction x - y.

val mul : int -> int -> int

mul x y is the multiplication x * y.

val div : int -> int -> int

div x y is the division x / y. See (/)[28.2] for details.

val rem : int -> int -> int

rem x y is the remainder x mod y. See (mod)[28.2] for details.

val succ : int -> int

succ x is add x 1.

val pred : int -> int

pred x is sub x 1.

val abs : int -> int

abs x is the absolute value of x. That is x if x is positive and neg x if x is negative.

**Warning.** This may be negative if the argument is Int.min_int[29.28].

val max_int : int

max_int is the greatest representable integer, $2^{\text{Sys.int_size}-1}-1$.

val min_int : int

min_int is the smallest representable integer, $-2^{\text{Sys.int_size}-1}$.

val logand : int -> int -> int

logand x y is the bitwise logical and of x and y.

val logor : int -> int -> int

logor x y is the bitwise logical or of x and y.

val logxor : int -> int -> int

logxor x y is the bitwise logical exclusive or of x and y.

val lognot : int -> int
## Sets

**type elt**

The type of the set elements.

**type t**

The type of sets.

**val empty : t**

The empty set.

**val add : elt -> t -> t**

add x s returns a set containing all elements of s, plus x. If x was already in s, s is returned unchanged (the result of the function is then physically equal to s).

**Before 4.03** Physical equality was not ensured.

**val singleton : elt -> t**

singleton x returns the one-element set containing only x.

**val remove : elt -> t -> t**

remove x s returns a set containing all elements of s, except x. If x was not in s, s is returned unchanged (the result of the function is then physically equal to s).

**Before 4.03** Physical equality was not ensured.

**val union : t -> t -> t**

Set union.

**val inter : t -> t -> t**

Set intersection.

**val disjoint : t -> t -> bool**

Test if two sets are disjoint.

**Since: 4.08**

**val diff : t -> t -> t**

Set difference: diff s1 s2 contains the elements of s1 that are not in s2.

**val cardinal : t -> int**

Return the number of elements of a set.

## Elements

**val elements : t -> elt list**

Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord compares`, where `Ord` is the argument given to `MoreLabels.Set.Make[28.35]`.
`lognot x` is the bitwise logical negation of x.

`val shift_left : int -> int -> int`
`shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n > Sys.int_size[29.60]`.

`val shift_right : int -> int -> int`
`shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n > Sys.int_size[29.60]`.

`val shift_rightshift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n > Sys.int_size[29.60]`.

## Predicates and comparisons

`val equal : int -> int -> bool`
`equal x y` is true if and only if `x == y`.

`val compare : int -> int -> int`
`compare x y` is `compare[28.2] x y` but more efficient.

`val min : int -> int -> int`
Return the smaller of the two arguments.

Since: 4.13

`val max : int -> int -> int`
Return the greater of the two arguments.

Since: 4.13

## Converting

`val to_float : int -> float`
`to_float x` is `x` as a floating point number.

`val of_float : float -> int`
`of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers.

`val to_string : int -> string`
### `val min_elt`: `t -> elt`

Return the smallest element of the given set (with respect to the `Ord compares` ordering), or raise `Not_found` if the set is empty.

### `val min_elt_opt`: `t -> elt` option

Return the smallest element of the given set (with respect to the `Ord compares` ordering), or `None` if the set is empty.

**Since:** 4.05

### `val max_elt`: `t -> elt`

Same as `MoreLabels.Set.S.min_elt` [28.35], but returns the largest element of the given set.

### `val max_elt_opt`: `t -> elt` option

Same as `MoreLabels.Set.S.min_elt_opt` [28.35], but returns the largest element of the given set.

**Since:** 4.05

### `val choose`: `t -> elt`

Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.

### `val choose_opt`: `t -> elt` option

Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.

**Since:** 4.05

## Searching

### `val find`: `elt -> t -> elt`

`find` `x s` returns the element of `s` equal to `x` (according to `Ord compares`), or raise `Not_found` if no such element exists.

**Since:** 4.01

### `val find_opt`: `elt -> t -> elt` option

`find_opt` `x s` returns the element of `s` equal to `x` (according to `Ord compares`), or `None` if no such element exists.

**Since:** 4.05

### `val find_first`: `f:(elt -> bool) -> t -> elt`

`find_first` `~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. For example, `find_first` (`f e -> Ord comparisons e x >= 0`) `s` will return the first element `e` of `s` where `Ord comparisons e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`.

**Since:** 4.05
`to_string` x is the written representation of x in decimal.

`val seeded_hash : int -> int -> int`

A seeded hash function for ints, with the same output value as `Hashtbl.seeded_hash[29.26]`. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded[29.26]`.

**Since:** 5.1

`val hash : int -> int`

An unseeded hash function for ints, with the same output value as `Hashtbl.hash[29.26]`. This function allows this module to be passed as argument to the functor `Hashtbl.Make[29.26]`.

**Since:** 5.1

## 29.29 Module Int32: 32-bit integers.

This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo $2^{32}$.

Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic.

Literals for 32-bit integers are suffixed by `l`:

```
let zero: int32 = 01
let one: int32 = 11
let m_one: int32 = -11
```

`val zero : int32`

The 32-bit integer 0.

`val one : int32`

The 32-bit integer 1.

`val minus_one : int32`

The 32-bit integer -1.

`val neg : int32 -> int32`

Unary negation.

`val add : int32 -> int32 -> int32`

Addition.
```hkl
val find_first_opt : f:(elt -> bool) ->
  t -> elt option
```

`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists.

**Since:** 4.05

```hkl
val find_last : f:(elt -> bool) ->
  t -> elt
```

`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists.

**Since:** 4.05

```hkl
val find_last_opt : f:(elt -> bool) ->
  t -> elt option
```

`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists.

**Since:** 4.05

## Traversing

```hkl
val iter : f:(elt -> unit) -> t -> unit
```

`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements.

```hkl
val fold : f:(elt -> 'acc -> 'acc) ->
  t -> init:'acc -> 'acc
```

`fold ~f s init` computes (`f xN ...` (`f x2` (`f x1 init`))...), where `x1 ... xN` are the elements of `s`, in increasing order.

## Transforming

```hkl
val map : f:(elt -> elt) ->
  t -> t
```

`map ~f s` is the set whose elements are `f a0, f a1... f aN`, where `a0, a1... aN` are the elements of `s`.

The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements.

If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.)

**Since:** 4.04

```hkl
val filter : f:(elt -> bool) -> t -> t
```
val sub : int32 -> int32 -> int32
Subtraction.

val mul : int32 -> int32 -> int32
Multiplication.

val div : int32 -> int32 -> int32
Integer division. This division rounds the real quotient of its arguments towards zero, as specified for (`/`)[28.2].

**Raises** `Division_by_zero` if the second argument is zero.

val unsigned_div : int32 -> int32 -> int32
Same as `Int32.div` [29.29], except that arguments and result are interpreted as *unsigned* 32-bit integers.

**Since:** 4.08

val rem : int32 -> int32 -> int32
Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division_by_zero`.

val unsigned/rem : int32 -> int32 -> int32
Same as `Int32.rem` [29.29], except that arguments and result are interpreted as *unsigned* 32-bit integers.

**Since:** 4.08

val succ : int32 -> int32
Successor. `Int32.succ x` is `Int32.add x Int32.one`.

val pred : int32 -> int32
Predecessor. `Int32pred` `x` is `Int32.sub x Int32.one`.

val abs : int32 -> int32
`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.

val max_int : int32
The greatest representable 32-bit integer, $2^{31} - 1$.

val min_int : int32
The smallest representable 32-bit integer, $-2^{31}$.

val logand : int32 -> int32 -> int32
Bitwise logical and.
`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).

**Before 4.03** Physical equality was not ensured.

`val filter_map : f:(elt -> elt option) ->
t -> t`

`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`.

For example,

`filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s` is the set of halves of the even elements of `s`.

If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. **Since: 4.11**

`val partition : f:(elt -> bool) ->
t -> t * t`

`partition ~f s` returns a pair of sets (`s1`, `s2`), where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`.

`val split : elt ->
t -> t * bool * t`

`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`.

## Predicates and comparisons

`val is_empty : t -> bool`

Test whether a set is empty or not.

`val mem : elt -> t -> bool`

`mem x s` tests whether `x` belongs to the set `s`.

`val equal : t -> t -> bool`

`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements.

`val compare : t -> t -> int`

Total ordering between sets. Can be used as the ordering function for doing sets of sets.
`val logor : int32 -> int32 -> int32`

Bitwise logical or.

`val logxor : int32 -> int32 -> int32`

Bitwise logical exclusive or.

`val lognot : int32 -> int32`

Bitwise logical negation.

`val shift_left : int32 -> int -> int32`

`Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`.

`val shift_right : int32 -> int -> int32`

`Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`.

`val shift_rightlogical: int32 -> int -> int32`

`Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`.

`val of_int : int -> int32`

Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo $2^{32}$.

`val to_int : int32 -> int`

Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo $2^{31}$, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact.

`val unsigned_to_int : int32 -> int` *option*

Same as `Int32.to_int[29.29]`, but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`.

**Since:** 4.08

`val of_float : float -> int32`

Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range `[Int32.min_int[29.29], Int32.max_int[29.29]]`, no exception is raised, and an unspecified, platform-dependent integer is returned.

`val to_float : int32 -> float`
val subset : t -> t -> bool

subset s1 s2 tests whether the set s1 is a subset of the set s2.

val for_all : f:(elt -> bool) -> t -> bool

for_all ~f s checks if all elements of the set satisfy the predicate f.

val exists : f:(elt -> bool) -> t -> bool

exists ~f s checks if at least one element of the set satisfies the predicate f.

Converting

val to_list : t -> elt list

to_list s is MoreLabels.Set.S.element s [28.35] s.

Since: 5.1

val of_list : elt list -> t

of_list l creates a set from a list of elements. This is usually more efficient than
folding add over the list, except perhaps for lists with many duplicated elements.

Since: 4.02

val to_seq_from : elt ->

t -> elt Seq.t

to_seq_from x s iterates on a subset of the elements of s in ascending order, from
x or above.

Since: 4.07

val to_seq : t -> elt Seq.t

Iterate on the whole set, in ascending order

Since: 4.07

val to_rev_seq : t -> elt Seq.t

Iterate on the whole set, in descending order

Since: 4.12

val add_seq : elt Seq.t -> t -> t

Add the given elements to the set, in order.

Since: 4.07

val of_seq : elt Seq.t -> t

Build a set from the given bindings

Since: 4.07

end

Output signature of the functor MoreLabels.Set.Make[28.35].
Convert the given 32-bit integer to a floating-point number.

`val of_string : string -> int32`

Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.

The `0u` prefix reads the input as an unsigned integer in the range `[0, 2\*Int32.max_int+1]`. If the input exceeds `Int32.max_int[29.29]` it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`.

The `_` (underscore) character can appear anywhere in the string and is ignored.

**Raises** Failure if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int32`.

`val of_string_opt : string -> int32 option`

Same as `of_string`, but return `None` instead of raising.

**Since:** 4.05

`val to_string : int32 -> string`

Return the string representation of its argument, in signed decimal.

`val bits_of_float : float -> int32`

Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa.

`val float_of_bits : int32 -> float`

Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`.

`type t = int32`

An alias for the type of 32-bit integers.

`val compare : t -> t -> int`

The comparison function for 32-bit integers, with the same specification as `compare[28.2]`. Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors `Set.Make[29.54]` and `Map.Make[29.35]`.

`val unsigned_compare : t -> t -> int`

Same as `Int32 compares[29.29]`, except that arguments are interpreted as unsigned 32-bit integers.

**Since:** 4.08

`val equal : t -> t -> bool`
module Make :
functor (Ord : OrderedType) -> S with type elt = Ord.t and type t =
Set.Make(Ord).t

Functor building an implementation of the set structure given a totally ordered type.

end

## 28.36 Module Mutex : Locks for mutual exclusion.

Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`):

```h
Mutex.lock m;
(* Critical section that operates over D *);
Mutex unlock m
```

### type t

The type of mutexes.

### val create : unit -> t

Return a new mutex.

### val lock : t -> unit

Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex.

**Before 4.12** `Sys_error` was not raised for recursive locking (platform-dependent behaviour)

**Raises** `Sys_error` if the mutex is already locked by the thread calling `Mutex.lock` [28.36].

### val try_lock : t -> bool

Same as `Mutex.lock` [28.36], but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`.

### val unlock : t -> unit

Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls `Mutex unlock` [28.36].

**Before 4.12** `Sys_error` was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread.

**Raises** `Sys_error` if the mutex is unlocked or was locked by another thread.
The equal function for `int32s`.

**Since: 4.03**

`val min : t -> t -> t`

Return the smaller of the two arguments.

**Since: 4.13**

`val max : t -> t -> t`

Return the greater of the two arguments.

**Since: 4.13**

`val seeded_hash : int -> t -> int`

A seeded hash function for 32-bit ints, with the same output value as `Hashtbl.seeded_hash[29.26]`. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded[29.26]`.

**Since: 5.1**

`val hash : t -> int`

An unseeded hash function for 32-bit ints, with the same output value as `Hashtbl.hash[29.26]`. This function allows this module to be passed as argument to the functor `Hashtbl.Make[29.26]`.

**Since: 5.1**

## 29.30 Module `Int64`: 64-bit integers.

This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo $2^{64}$.

Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic.

Literals for 64-bit integers are suffixed by `L`:

```
let zero: int64 = 0L
let one: int64 = 1L
let m_one: int64 = -1L
```

`val zero : int64`

The 64-bit integer 0.

`val one : int64`
```h
val protect : t -> (unit -> 'a) -> 'a
```

protect mutex f runs f() in a critical section where mutex is locked (using Mutex.lock[28.36]); it then takes care of releasing mutex, whether f() returned a value or raised an exception.

The unlocking operation is guaranteed to always takes place, even in the event an
asynchronous exception (e.g. Sys.Break[28.55]) is raised in some signal handler.

Since: 5.1

## 28.37 Module Nativeint: Processor-native integers.

This module provides operations on the type `nativeint` of signed 32-bit integers (on 32-bit platforms) or signed 64-bit integers (on 64-bit platforms). This integer type has exactly the same width as that of a pointer type in the C compiler. All arithmetic operations over `nativeint` are taken modulo $2^{32}$ or $2^{64}$ depending on the word size of the architecture.

Performance notice: values of type `nativeint` occupy more memory space than values of type `int`, and arithmetic operations on `nativeint` are generally slower than those on `int`. Use `nativeint` only when the application requires the extra bit of precision over the `int` type.

Literals for native integers are suffixed by n:

```h
let zero: nativeint = 0n
let one: nativeint = 1n
let m_one: nativeint = -1n
```

```h
val zero : nativeint
```

The native integer 0.

```h
val one : nativeint
```

The native integer 1.

```h
val minus_one : nativeint
```

The native integer -1.

```h
val neg : nativeint -> nativeint
```

Unary negation.

```h
val add : nativeint -> nativeint -> nativeint
```

Addition.

```h
val sub : nativeint -> nativeint -> nativeint
```

Subtraction.

```h
val mul : nativeint -> nativeint -> nativeint
```
The 64-bit integer 1.

val minus_one: int64

The 64-bit integer -1.

val neg: int64 -> int64

Unary negation.

val add: int64 -> int64 -> int64

Addition.

val sub: int64 -> int64 -> int64

Subtraction.

val mul: int64 -> int64 -> int64

Multiplication.

val div: int64 -> int64 -> int64

Integer division.

**Raises** `Division_by_zero` if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for `(/)[28.2]`.

val unsigned_div: int64 -> int64 -> int64

Same as `Int64.div[29.30]`, except that arguments and result are interpreted as *unsigned* 64-bit integers.

**Since:** 4.08

val rem: int64 -> int64 -> int64

Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division_by_zero`.

val unsigned/rem: int64 -> int64 -> int64

Same as `Int64.rem[29.30]`, except that arguments and result are interpreted as *unsigned* 64-bit integers.

**Since:** 4.08

val succ: int64 -> int64

Successor. `Int64.succ x` is `Int64.add x Int64.one`.

val pred: int64 -> int64

Predecessor. `Int64eel` is `Int64.sub x Int64.one`.

val abs: int64 -> int64
Multiplication.

### `val div : nativeint -> nativeint -> nativeint`

Integer division. This division rounds the real quotient of its arguments towards zero, as specified for (`/`)[27.2].

**Raises** `Division_by_zero` if the second argument is zero.

### `val unsigned_div : nativeint -> nativeint -> nativeint`

Same as `Nativeint.div`[28.37], except that arguments and result are interpreted as unsigned native integers.

**Since:** 4.08

### `val rem : nativeint -> nativeint -> nativeint`

Integer remainder. If `y` is not zero, the result of `Nativeint.rem x y` satisfies the following properties: `Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y` and `x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y) (Nativeint.rem x y)`. If `y = 0`, `Nativeint.rem x y` raises `Division_by_zero`.

### `val unsignedRem : nativeint -> nativeint -> nativeint`

Same as `Nativeint.rem`[28.37], except that arguments and result are interpreted as unsigned native integers.

**Since:** 4.08

### `val succ : nativeint -> nativeint`

Successor. `Nativeint.succ x` is `Nativeint.add x Nativeint.one`.

### `val pred : nativeint -> nativeint`

Predecessor. `Nativeintpred x` is `Nativeint.sub x Nativeint.one`.

### `val abs : nativeint -> nativeint`

`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.

### `val size : int`

The size in bits of a native integer. This is equal to 32 on a 32-bit platform and to 64 on a 64-bit platform.

### `val max_int : nativeint`

The greatest representable native integer, either $2^{31} - 1$ on a 32-bit platform, or $2^{63} - 1$ on a 64-bit platform.

### `val min_int : nativeint`

The smallest representable native integer, either $-2^{31}$ on a 32-bit platform, or $-2^{63}$ on a 64-bit platform.
`abs` x is the absolute value of x. On `min_int` this is `min_int` itself and thus remains negative.

val max_int : int64

The greatest representable 64-bit integer, $2^{63} - 1$.

val min_int : int64

The smallest representable 64-bit integer, $-2^{63}$.

val logand : int64 -> int64 -> int64

Bitwise logical and.

val logor : int64 -> int64 -> int64

Bitwise logical or.

val logxor : int64 -> int64 -> int64

Bitwise logical exclusive or.

val lognot : int64 -> int64

Bitwise logical negation.

val shift_left : int64 -> int -> int64

`Int64.shift_left` x y shifts x to the left by y bits. The result is unspecified if $y < 0$ or $y >= 64$.

val shift_right : int64 -> int -> int64

`Int64.shift_right` x y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if $y < 0$ or $y >= 64$.

val shift_right{logical : int64 -> int -> int64

`Int64.shift_right_logical` x y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if $y < 0$ or $y >= 64$.

val of_int : int -> int64

Convert the given integer (type `int`) to a 64-bit integer (type `int64`).

val to_int : int64 -> int

Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo $2^{63}$, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo $2^{31}$, i.e. the top 33 bits are lost during the conversion.

val unsigned_to_int : int64 -> int option
val logand : nativeint -> nativeint -> nativeint
Bitwise logical and.

val logor : nativeint -> nativeint -> nativeint
Bitwise logical or.

val logxor : nativeint -> nativeint -> nativeint
Bitwise logical exclusive or.

val lognot : nativeint -> nativeint
Bitwise logical negation.

val shift_left : nativeint -> int -> nativeint
Nativeint.shift_left x y shifts x to the left by y bits. The result is unspecified if y < 0 or y >= bitsize, where bitsize is 32 on a 32-bit platform and 64 on a 64-bit platform.

val shift_right : nativeint -> int -> nativeint
Nativeint.shift_right x y shifts x to the right by y bits. This is an arithmetic shift: the
sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0
or y >= bitsize.

val shift_right logical : nativeint -> int -> nativeint
Nativeint.shift_right_logica x y shifts x to the right by y bits. This is a logical shift:
zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y
< 0 or y >= bitsize.

val of_int : int -> nativeint
Convert the given integer (type *int*) to a native integer (type *nativeint*).

val to_int : nativeint -> int
Convert the given native integer (type *nativeint*) to an integer (type *int*). The high-order bit is lost during the conversion.

val unsigned_to_int : nativeint -> int option
Same as Nativeint.to_int[28.37], but interprets the argument as an unsigned integer.
Returns None if the unsigned value of the argument cannot fit into an int.

Since: 4.08

val of_float : float -> nativeint
Convert the given floating-point number to a native integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range [Nativeint.min_int[28.37], Nativeint.max_int[28.37]], no exception is raised, and an unspecified, platform-dependent integer is returned.
Same as `Int64.to_int[29.30]`, but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`.

**Since: 4.08**

**val of_float: float -> int64**

Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range `[Int64.min_int[29.30], Int64.max_int[29.30]]`, no exception is raised, and an unspecified, platform-dependent integer is returned.

**val to_float: int64 -> float**

Convert the given 64-bit integer to a floating-point number.

**val of_int32: int32 -> int64**

Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`).

**val to_int32: int64 -> int32**

Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo $2^{32}$, i.e. the top 32 bits are lost during the conversion.

**val of_nativeint: nativeint -> int64**

Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`).

**val to_nativeint: int64 -> nativeint**

Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo $2^{32}$. On 64-bit platforms, the conversion is exact.

**val of_string: string -> int64**

Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.

The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds `Int64.max_int[29.30]` it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`.

The `_` (underscore) character can appear anywhere in the string and is ignored.

**Raises Failure** if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int64`.

**val of_string_opt: string -> int64 option**

Same as `of_string`, but return `None` instead of raising.

**Since: 4.05**

**val to_string: int64 -> string**
### `val to_float`: `nativeint` -> `float`

Convert the given native integer to a floating-point number.

### `val of_int32`: `int32` -> `nativeint`

Convert the given 32-bit integer (type `int32`) to a native integer.

### `val to_int32`: `nativeint` -> `int32`

Convert the given native integer to a 32-bit integer (type `int32`). On 64-bit platforms, the 64-bit native integer is taken modulo $2^{32}$, i.e. the top 32 bits are lost. On 32-bit platforms, the conversion is exact.

### `val of_string`: `string` -> `nativeint`

Convert the given string to a native integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.

The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Nativeint.max_int+1]`. If the input exceeds `Nativeint.max_int` [28.37] it is converted to the signed integer `Int64.min_int + input - Nativeint.max_int - 1`.

**Raises** Failure if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `nativeint`.

### `val of_string_opt`: `string` -> `nativeint` option

Same as `of_string`, but return `None` instead of raising.

**Since:** 4.05

### `val to_string`: `nativeint` -> `string`

Return the string representation of its argument, in decimal.

### `type t = nativeint`

An alias for the type of native integers.

### `val compare`: `t` -> `t` -> `int`

The comparison function for native integers, with the same specification as `compare` [27.2]. Along with the type `t`, this function `compare` allows the module `Nativeint` to be passed as argument to the functors `Set.Make` [28.49] and `Map.Make` [28.33].

### `val unsigned_compare`: `t` -> `t` -> `int`

Same as `Nativeint compares` [28.37], except that arguments are interpreted as unsigned native integers.

**Since:** 4.08

### `val equal`: `t` -> `t` -> `bool`
Return the string representation of its argument, in decimal.

`val bits_of_float : float -> int64`

Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa.

`val float_of_bits : int64 -> float`

Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`.

`type t = int64`

An alias for the type of 64-bit integers.

`val compare : t -> t -> int`

The comparison function for 64-bit integers, with the same specification as `compare` [28.2]. Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors `Set.Make` [29.54] and `Map.Make` [29.35].

`val unsigned_compare : t -> t -> int`

Same as `Int64 comparisons` [29.30], except that arguments are interpreted as unsigned 64-bit integers.

**Since:** 4.08

`val equal : t -> t -> bool`

The equal function for `int64s`.

**Since:** 4.03

`val min : t -> t -> t`

Return the smaller of the two arguments.

**Since:** 4.13

`val max : t -> t -> t`

Return the greater of the two arguments.

**Since:** 4.13

`val seeded_hash : int -> t -> int`

A seeded hash function for 64-bit ints, with the same output value as `Hashtbl.seeded_hash` [29.26]. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded` [29.26].

**Since:** 5.1

`val hash : t -> int`
The equal function for native ints.

**Since: 4.03**

`val min : t -> t -> t`

Return the smaller of the two arguments.

**Since: 4.13**

`val max : t -> t -> t`

Return the greater of the two arguments.

**Since: 4.13**

`val seeded_hash : int -> t -> int`

A seeded hash function for native ints, with the same output value as `Hashtbl.seeded_hash[28.24]`. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded[28.24]`.

**Since: 5.1**

`val hash : t -> int`

An unseeded hash function for native ints, with the same output value as `Hashtbl.hash[28.24]`. This function allows this module to be passed as argument to the functor `Hashtbl.Make[28.24]`.

**Since: 5.1**

## 28.38 Module Oo: Operations on objects

`val copy : (< .. > as 'a) -> 'a`

`Oo.copy` o returns a copy of object o, that is a fresh object with the same methods and instance variables as o.

**Alert unsynchronized_access.** Unsynchronized accesses to mutable objects are a programming error.

`val id : < .. > -> int`

Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures.
An unseeded hash function for 64-bit ints, with the same output value as `Hashtbl.hash[29.26]`. This function allows this module to be passed as argument to the functor `Hashtbl.Make[29.26]`.

**Since: 5.1**

## 29.31 Module Lazy : Deferred computations.

```python
type 'a t = 'a CamlinternalLazy.t
```

A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy(expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazypattern` also computes the underlying expression and tries to bind it to `pattern`:

```python
let lazy_option_map f x =
match x with
| lazy (Some x) -> Some (Lazy.force f x)
| _ -> None
```

**Note:** If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed.

**Note:** `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead.

**Note:** `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, `systhreads` or `domains`, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified.

**Note:** if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(... (lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker.

### exception Undefined

Raised when forcing a suspension concurrently from multiple fibers, `systhreads` or `domains`, or when the suspension tries to force itself recursively.

```python
val force : 'a t -> 'a
```
## 28.39 Module Option : Option values.

Option values explicitly indicate the presence or absence of a value.

**Since: 4.08**

### Options

type 'a t = 'a option =

| None

| Some of 'a

The type for option values. Either `None` or a value `Some v`.

val none : 'a option

none is `None`.

val some : 'a -> 'a option

some `v` is `Some v`.

val value : 'a option -> default:'a -> 'a

value `o` ~default is `v` if `o` is `Some v` and default otherwise.

val get : 'a option -> 'a

get `o` is `v` if `o` is `Some v` and raise otherwise.

Raises `Invalid_argument` if `o` is `None`.

val bind : 'a option -> ('a -> 'b option) -> 'b option

bind `o` `f` is `f` `v` if `o` is `Some v` and `None` if `o` is `None`.

val join : 'a option option -> 'a option

join `oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise.

val map : ('a -> 'b) -> 'a option -> 'b option

map `f` `o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`.

val fold : none:'a -> some:( 'b -> 'a) -> 'b option -> 'a

fold ~none ~some `o` is `none` if `o` is `None` and `some v` if `o` is `Some v`.

val iter : ('a -> unit) -> 'a option -> unit

iter `f` `o` is `f` `v` if `o` is `Some v` and () otherwise.
`force` x forces the suspension x and returns its result. If x has already been forced, `Lazy.force` x returns the same value again without recomputing it. If it raised an exception, the same exception is raised again.

**Raises** `Undefined` (see `Lazy.Undefined`[29.31]).

## Iterators

`val map : ('a -> 'b) -> 'a t -> 'b t`

`map` f x returns a suspension that, when forced, forces x and applies f to its value.

It is equivalent to `lazy (f (Lazy.force x))`.

**Since:** 4.13

## Reasoning on already-forced suspensions

`val is_val : 'a t -> bool`

`is_val` x returns true if x has already been forced and did not raise an exception.

**Since:** 4.00

`val from_val : 'a -> 'a t`

`from_val` v evaluates v first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases.

**Since:** 4.00

`val map_val : ('a -> 'b) -> 'a t -> 'b t`

`map_val` f x applies f directly if x is already forced, otherwise it behaves as `map f x`.

When x is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result.

If f raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the chunk otherwise.

If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`.

**Since:** 4.13

## Advanced

The following definitions are for advanced uses only; they require familiarity with the lazy compilation scheme to be used appropriately.

`val from Fun : (unit -> 'a) -> 'a t`
Predicates and comparisons

val is_none : 'a option -> bool
is_none o is true if and only if o is None.

val is_some : 'a option -> bool
is_some o is true if and only if o is Some o.

val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool
equal eq o0 o1 is true if and only if o0 and o1 are both None or if they are Some v0 and
Some v1 and eq v0 v1 is true.

val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int
compare cmp o0 o1 is a total order on options using cmp to compare values wrapped by
Some _ . None is smaller than Some _ values.

Converting

val to_result : none:'e -> 'a option -> ('a, 'e) result
to_result ~none o is Ok v if o is Some v and Error none otherwise.

val to_list : 'a option -> 'a list
to_list o is [] if o is None and [v] if o is Some v.

val to_seq : 'a option -> 'a Seq.t
to_seq o is o as a sequence. None is the empty sequence and Some v is the singleton
sequence containing v.

28.40 Module Out_channel : Output channels.

This module provides functions for working with output channels.
See the example section[28.44] below.

Since: 4.14

Channels

type t = out_channel
The type of output channel.

type open_flag = open_flag =
| Open_rdonly
open for reading.
`from Fun f` is the same as `lazy (f())` but slightly more efficient.

It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from Fun (fun () -> expr)` than `lazy expr`.

**Since:** 4.00

```hml
val force_val : 'a t -> 'a
```

`force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it.

If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or `Lazy.Undefined[29.31]`.

**Raises**

* `Undefined` if the forcing of `x` tries to force `x` itself recursively.

* `Undefined` (see `Lazy.Undefined[29.31]`).

## 29.32 Module Lexing: The run-time library for lexers generated by ocamllex.

### Positions

```hml
type position =
  { pos fname : string ;
    pos_lnum : int ;
    pos_bol : int ;
    pos_cnum : int ;
  }
```

A value of type `position` describes a point in a source file. `pos fname` is the file name; `pos lnum` is the line number; `pos bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos cnum` and `pos bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide).

See the documentation of type `lexbuf` for information about how the lexing engine will manage positions.

```hml
val dummy_pos : position
```

A value of type `position`, guaranteed to be different from any valid position.
| Open_wronly
  open for writing.

| Open_append
  open for appending: always write at end of file.

| Open_creat
  create the file if it does not exist.

| Open_trunc
  empty the file if it already exists.

| Open_excl
  fail if Open_creat and the file already exists.

| Open_binary
  open in binary mode (no conversion).

| Open_text
  open in text mode (may perform conversions).

| Open_nonblock
  open in non-blocking mode.

Opening modes for `Out_channel.open_gen[28.40]`.

val stdout : t
The standard output for the process.

val stderr : t
The standard error output for the process.

val open_bin : string -> t
Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.

val open_text : string -> t
Same as `Out_channel.open_bin[28.40]`, but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like `Out_channel.open_bin[28.40]`.

val open_gen : open_flag list -> int -> string -> t
`open_gen` mode `perm` filename opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. `Out_channel.open_text[28.40]` and `Out_channel.open_bin[28.40]` are special cases of this function.
## Parser buffers

```typescript
type lexbuf =
{
    refill_buff : lexbuf -> unit ;
    mutable lex_buffer : bytes ;
    mutable lex_buffer_len : int ;
    mutable lex_abs_pos : int ;
    mutable lex_start_pos : int ;
    mutable lex_current_pos : int ;
    mutable lex_last_pos : int ;
    mutable lex_last_action : int ;
    mutable lex_eof_reached : bool ;
    mutable lex_mem : int array ;
    mutable lex_start_p : position ;
    mutable lex_current_p : position ;
}
```

The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input.

Lexers can optionally maintain the `lex_current_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_current_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_current_p` are not needed.

Position tracking mode works as follows. At each token, the lexing engine will copy `lex_current_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_current_p` by updating it with the number of characters read since the start of the lexbuf. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line - see also `new_line`).

### `val from_channel`: `?with positions:bool -> in_channel -> lexbuf`

Create a lexer buffer on the given input channel. `Lexing.from_channel` in `chan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position.

### `val from_string`: `?with positions:bool -> string -> lexbuf`

Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached.

### `val from_function`: `?with positions:bool -> (bytes -> int -> int) -> lexbuf`
val `with_open_bin`: `string -> (t -> 'a) -> 'a`

`with_open_bin` fn f opens a channel `oc` on file fn and returns f `oc`. After f returns, either with a value or by raising an exception, `oc` is guaranteed to be closed.

val `with_open_text`: `string -> (t -> 'a) -> 'a`

Like `Out_channel.with_open_bin[28.40]`, but the channel is opened in text mode (see `Out_channel.open_text[28.40]`).

val `with_open_gen`: `open_flag list -> int -> string -> (t -> 'a) -> 'a`

Like `Out_channel.with_open_bin[28.40]`, but can specify the opening mode and file permission, in case the file must be created (see `Out_channel.open_gen[28.40]`).

val `close`: `t -> unit`

Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `Out_channel.close[28.40]` and `Out_channel.flush[28.40]`, which do nothing when applied to an already closed channel. Note that `Out_channel.close[28.40]` may raise `Sys_error` if the operating system signals an error when flushing or closing.

val `close_noerr`: `t -> unit`

Same as `Out_channel.close[28.40]`, but ignore all errors.

## Output

val `output_char`: `t -> char -> unit`

Write the character on the given output channel.

val `output_bytes`: `t -> int -> unit`

Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.

val `output_string`: `t -> string -> unit`

Write the string on the given output channel.

val `output_bytes`: `t -> bytes -> unit`

Write the byte sequence on the given output channel.

## Advanced output

val `output`: `t -> bytes -> int -> int -> unit`

`output` `oc` `buf` `pos` `len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input.

**val set_position : lexbuf -> position -> unit**

Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos fname`. See `Lexing.set_filename[29.32]` for changing this field.

**Since: 4.11**

**val set_filename : lexbuf -> string -> unit**

Set filename in the initial tracked position to `file` in `lexbuf`.

**Since: 4.11**

**val with_pospositions : lexbuf -> bool**

Tell whether the lexer buffer keeps track of position fields `lex_current` / `lex_start`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`).

When `with_pospositions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances.

## Functions for lexer semantic actions

The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function.

**val lexeme : lexbuf -> string**

`Lexing.lexeme` `lexbuf` returns the string matched by the regular expression.

**val lexeme_char : lexbuf -> int -> char**

`Lexing.lexeme_char` `lexbuf` `i` returns character number `i` in the matched string.

**val lexeme_start : lexbuf -> int**

`Lexing.lexeme_start` `lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0.

**val lexeme_end : lexbuf -> int**

`Lexing.lexeme_end` `lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0.

**val lexeme_start_p : lexbuf -> position**
`val output_substring : t -> string -> int -> int -> unit`

Same as `Out_channel.output[28.40]` but take a string as argument instead of a byte sequence.

## Flushing

`val flush : t -> unit`

Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.

`val flush_all : unit -> unit`

Flush all open output channels; ignore errors.

## Seeking

`val seek : t -> int64 -> unit`

`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.

`val pos : t -> int64`

Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results).

For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with

`Out_channel.pos[28.40]`, then going back to this position using `Out_channel.seek[28.40]` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.

## Attributes

`val length : t -> int64`

Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.

`val set_binary_mode : t -> bool -> unit`

`set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output.

`set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`.
Like `lexeme_start`, but return a complete `position` instead of an offset. When `position` tracking is disabled, the function returns `dummy_pos`.

`val lexeme_end_p : lexbuf -> position`

Like `lexeme_end`, but return a complete `position` instead of an offset. When `position` tracking is disabled, the function returns `dummy_pos`.

`val new_line : lexbuf -> unit`

Update the `lex_current_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled.

**Since:** 3.11

## Miscellaneous functions

`val flush_input : lexbuf -> unit`

Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill.

## 29.33 Module List : List operations.

Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses.

The above considerations can usually be ignored if your lists are not longer than about 10000 elements.

The labeled version of this module can be used as described in the `StdLabels`[29.57] module.

`type 'a t = 'a list =`

| []

| (:) of 'a * 'a list

An alias for the type of lists.

`val length : 'a list -> int`

Return the length (number of elements) of the given list.

`val compare_length : 'a list -> 'b list -> int`

Compare the lengths of two lists. `compare_length` 11 12 is equivalent to `compare` (length 11) (length 12), except that the computation stops after reaching the end of the shortest list.

**Since:** 4.05
This function has no effect under operating systems that do not distinguish between text mode and binary mode.

val set_buffered : t -> bool -> unit

set_buffered oc true sets the channel oc to *buffered* mode. In this mode, data output on oc will be buffered until either the internal buffer is full or the function Out_channel.flush[28.40] or Out_channel.flush_all[28.40] is called, at which point it will be sent to the output device.

set_buffered oc false sets the channel oc to *unbuffered* mode. In this mode, data output on oc will be sent to the output device immediately.

All channels are open in *buffered* mode by default.

val is_buffered : t -> bool

is_buffered oc returns whether the channel oc is buffered (see Out_channel.set_buffered[28.40]).

val isatty : t -> bool

isatty oc is true if oc refers to a terminal or console window, false otherwise.

Since: 5.1

## Examples

Writing the contents of a file:

let write_file file s =
    Out_channel.with_open_bin file
    (fun oc -> Out_channel.output_string oc s))

## 28.41 Module Parsing: The run-time library for parsers generated by ocamlyacc.

val symbol_start : unit -> int

symbol_start and Parsing symbol_end [28.41] are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: symbol_start() returns the offset of the first character; symbol_end() returns the offset after the last character. The first character in a file is at offset 0.

val symbol_end : unit -> int

See Parsing symbol_start [28.41].

val rhs_start : int -> int
val compare_length_with : 'a list -> int -> int

Compare the length of a list to an integer. `compare_length_with 1 len` is equivalent to `compare (length 1) len`, except that the computation stops after at most `len` iterations on the list.

**Since:** 4.05

val is_empty : 'a list -> bool

`is_empty` `l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with 1 0 = 0`.

**Since:** 5.1

val cons : 'a -> 'a list -> 'a list

`cons x xs` is `x :: xs`

**Since:** 4.03 (4.05 in ListLabels)

val singleton : 'a -> 'a list

`singleton` `x` returns the one-element list `[x]`.

**Since:** 5.4

val hd : 'a list -> 'a

Return the first element of the given list.

**Raises** Failure if the list is empty.

val tl : 'a list -> 'a list

Return the given list without its first element.

**Raises** Failure if the list is empty.

val nth : 'a list -> int -> 'a

Return the `n`-th element of the given list. The first element (head of the list) is at position 0.

**Raises**

* Failure if the list is too short.

* `Invalid_argument` if `n` is negative.

val nth_opt : 'a list -> int -> 'a option

Return the `n`-th element of the given list. The first element (head of the list) is at position 0.

Return `None` if the list is too short.

**Since:** 4.05

**Raises** `Invalid_argument` if `n` is negative.

val rev : 'a list -> 'a list