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.

```c
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.

```c
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. Default: 15.

```c
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.

```c
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:

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

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

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

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

* `0x010` Heap compaction.

* `0x020` Change of GC parameters.

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

* `0x080` Calling of finalisation functions.

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

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

* `0x400` Output GC statistics at program exit. Default: 0.

```c
max_overhead : int;
```
module Make :

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

Functor building an implementation of a weak hash table

module MakeSeeded :

functor (H : Hashtbl.SeededHashedType) -> Ephemeron.SeededS with type key = H.t array

Functor building an implementation of a weak hash table. The seed is similar to the one of `Hashtbl.MakeSeeded[29.26]`.

module Bucket :

sig

type ('k, 'd) t

A bucket is a mutable "list" of ephemerons.

val make : unit -> ('k, 'd) t

Create a new bucket.

val add : ('k, 'd) t -> 'k array -> 'd -> unit

Add an ephemeron to the bucket.

val remove : ('k, 'd) t -> 'k array -> unit

remove b k removes from b the most-recently added ephemeron with keys k, or does nothing if there is no such ephemeron.

val find : ('k, 'd) t -> 'k array -> 'd option

Returns the data of the most-recently added ephemeron with the given keys, or `None` if there is no such ephemeron.

val length : ('k, 'd) t -> int

Returns an upper bound on the length of the bucket.

val clear : ('k, 'd) t -> unit

Remove all ephemerons from the bucket.

end

end

Ephemerons with arbitrary number of keys of the same type.
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. If compaction is permanently disabled, it is strongly suggested to set `allocation_policy` to 2. Default: 500.

`stack_limit`: `int`;

The maximum size of the fiber stacks (in words). Default: 1024k.

`allocation_policy`: `int`;

The policy used for allocating in the major heap. Possible values are 0, 1 and 2.

* 0 is the next-fit policy, which is usually fast but can result in fragmentation, increasing memory consumption.

* 1 is the first-fit policy, which avoids fragmentation but has corner cases (in certain realistic workloads) where it is sensibly slower.

* 2 is the best-fit policy, which is fast and avoids fragmentation. In our experiments it is faster and uses less memory than both next-fit and first-fit. (since OCaml 4.10)

The default is best-fit.

On one example that was known to be bad for next-fit and first-fit, next-fit takes 28s using 855Mio of memory, first-fit takes 47s using 566Mio of memory, best-fit takes 27s using 545Mio of memory.

**Note:** If you change to next-fit, you may need to reduce the `space_overhead` setting, for example using 80 instead of the default 120 which is tuned for best-fit. Otherwise, your program will need more memory.

**Note:** changing the allocation policy at run-time forces a heap compaction, which is a lengthy operation unless the heap is small (e.g. at the start of the program).

Default: 2.

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. Default: 1.

Since: 4.03

`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
## 29.21 Module Filename : Operations on file names.

**`val current_dir_name : string`**

The conventional name for the current directory (e.g. `..` in Unix).

**`val parent_dir_name : string`**

The conventional name for the parent of the current directory (e.g. `..` in Unix).

**`val dir_sep : string`**

The directory separator (e.g. `/` in Unix).

**Since: 3.11.2**

**`val concat : string -> string -> string`**

`concat dir file` returns a file name that designates file `file` in directory `dir`.

**`val is_relative : string -> bool`**

Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`).

**`val is_implicit : string -> bool`**

Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory.

**`val check_suffix : string -> string -> bool`**

`check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`.

Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase CHAR` . Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.

**`val chop_suffix : string -> string -> string`**

`chop_suffix name suff` removes the suffix `suff` from the filename `name`.

**Raises Invalid_argument if name does not end with the suffix suff.**

**`val chop_suffix_opt : suffix: string -> string -> string`**

`chop_suffix_opt ~suffix filename` removes the suffix from the filename if possible, or returns `None` if the filename does not end with the suffix.

Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase CHAR` . Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows.

**Since: 4.08**
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. When a custom value is allocated on the minor heap and holds more than this many bytes, only this value is counted against `custom_minor_ratio` and the rest is directly counted against `custom_major_ratio`. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. `bigarrays`). Default: 8192 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 represent the program's total memory stats. This function causes a full major collection.

`val quick_stat: unit -> stat`

Same as `stat` except that `live_words`, `live_blocks`, `free_words`, `free_blocks`, `largest_free`, and `fragments` are set to 0. Due to per-domain buffers it may only represent the state of the program's total memory usage since the last minor collection. This function is much faster than `stat` because it does not need to trigger a full major collection.

`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 extension : string -> string

extension name is the shortest suffix ext of name0 where:

* name0 is the longest suffix of name that does not contain a directory separator;

* ext starts with a period;

* ext is preceded by at least one non-period character in name0.

If such a suffix does not exist, extension name is the empty string.

**Since: 4.04**

val remove extension : string -> string

Return the given file name without its extension, as defined in Filename.extension[29.21].

If the extension is empty, the function returns the given file name.

The following invariant holds for any file name s:

remove extension s ~ extension s = s

**Since: 4.04**

val chop extension : string -> string

Same as Filename.remove extension [29.21], but raise Invalid_argument if the given name has an empty extension.

val basename : string -> string

Split a file name into directory name / base file name. If name is a valid file name, then concat (dirname name) (basename name) returns a file name which is equivalent to name.

Moreover, after setting the current directory to dirname name (with Sys.chdir[29.60]), references to basename name (which is a relative file name) designate the same file as name before the call to Sys.chdir[29.60].

This function conforms to the specification of POSIX.1-2008 for the basename utility.

val dirname : string -> string

See Filename.basename[29.21]. This function conforms to the specification of POSIX.1-2008 for the dirname utility.

val null : string

null is "/dev/null" on POSIX and "NUL" on Windows. It represents a file on the OS that discards all writes and returns end of file on reads.

**Since: 4.10**

val temp_file : ?temp_diryor string -> string -> string -> string
**val get : unit -> control**

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

**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 }
```

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

**val minor : unit -> unit**

Trigger a minor collection.

**val major_slice : int -> int**

`major_slice 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.

**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**
`temp_file` prefix suffix returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of `Filename.get_temp_dir_name[29.21]`. The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called.

**Before 3.11.2** no `?temp_dir` optional argument

**Raises** `Sys_error` if the file could not be created.

```perl
val open_temp_file :
    ?mode:open_flag list ->
    ?perms:int ->
    ?temp_dir:string -> string -> string -> string * out_channel
```

Same as `Filename.temp_file[29.21]`, but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open_append`, `Open_binary`, and `Open_text`. The default is `[Open_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`).

**Before 4.03** no `?perms` optional argument

**Before 3.11.2** no `?temp_dir` optional argument

**Raises** `Sys_error` if the file could not be opened.

```perl
val temp_dir : ?temp_dir:string -> ?perms:int -> string -> string -> string

temp_dir prefix suffix creates and returns the name of a fresh temporary directory with
permissions `perms` (defaults to `0o700`) inside `temp_dir`. The base name of the temporary
directory is formed by concatenating `prefix`, then a suitably chosen integer number, then
`suffix`. The optional argument `temp_dir` indicates the temporary directory to use,
defaulting to the current result of `Filename.get_temp_dir_name[29.21]`. The temporary
directory is created empty, with permissions `0o700` (readable, writable, and searchable only
by the file owner). The directory is guaranteed to be different from any other directory that
existed when `temp_dir` was called.
```

If `temp_dir` does not exist, this function does not create it. Instead, it raises `Sys_error`.

**Since:** 5.1

**Raises** `Sys_error` if the directory could not be created.

```perl
val get_temp_dir_name : unit -> string

The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment
variable, or `/tmp` if the variable is not set.
```
`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 Gcoppopp` (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 Gcopp`

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[28.53]`, `Bytes.make[28.8]`, `Bytes.create[28.8]`, `Array.make[28.2]`, and `ref[27.2]` are guaranteed to be heap-allocated and non-constant except when the length argument is 0.

```hml
val finalise_last : (unit -> unit) -> 'a -> unit
```
Under Windows, the value returned by `GetTempPath2` (if available) or `GetTempPath`.

The temporary directory can be changed with `Filename.set_temp_dir_name[29.21]`.

Under Windows, before `OCaml 5.4`, it would return the value of the `TEMP` environment variable, or `"."` if the variable was not set.

**Since: 4.00**

**val set_temp_dir_name : string -> unit**

Change the temporary directory returned by `Filename.get_temp_dir_name[29.21]` and used by `Filename.temp_file[29.21]` and `Filename.open_temp_file[29.21]`. The temporary directory is a domain-local value which is inherited by child domains.

**Since: 4.00**

**val quote : string -> string**

Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions.

**val quote_command :**

`string ->`

`?stdin: string -> ?stdout: string -> ?stderr: string -> string list -> string`

`quote_command cmd args` returns a quoted command line, suitable for use as an argument to `Sys.command[29.60]`, `Unix.system[31.1]`, and the `Unix.open_process[31.1]` functions.

The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty.

The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`.

Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using `Filename.quote[29.21]`, then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by `Sys.command[29.60]`.

**Since: 4.10**

**Raises Failure** if the command cannot be escaped on the current platform.
same as `Gc_finalise[28.23]` 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[28.23]` 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[28.23]` are always called before the finalisation functions attached with `Gc_finalise_last[28.23]`.

**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 each 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 each major GC cycle, not caused by `f` itself, starting with the current cycle or the next one. A value of type `alarm` is returned that you can use to call `delete_alarm`.

**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**

```hkl
    type allocation_source =
        | Normal
        | Marshal
        | Custom
```

```hkl
    type allocation = private
    { n Samples: int;
```

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

```hkl
    size: int;
```
## 29.22 Module Float: Floating-point arithmetic.

OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 / .0.0`, `neg_infinity` for `-1.0 / .0.0`, and `nan` ('not a number') for `0.0 / .0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 / .infinity` is 0.0, basic arithmetic operations (`+`, `-`, `*`, `/`) with `nan` as an argument return `nan`, ...

**Since:** 4.07

**val zero : float**

The floating point 0.

**Since:** 4.08

**val one : float**

The floating-point 1.

**Since:** 4.08

**val minus_one : float**

The floating-point -1.

**Since:** 4.08

**val neg : float -> float**

Unary negation.

**val add : float -> float -> float**

Floating-point addition.

**val sub : float -> float -> float**

Floating-point subtraction.

**val mul : float -> float -> float**

Floating-point multiplication.

**val div : float -> float -> float**

Floating-point division.

**val fma : float -> float -> float -> float**

`fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation.

On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software
The size of the block, in words, excluding the header.

source : `allocation_source`;

The type 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.

```typescript
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.

When using threads, it is guaranteed that allocation callbacks are always run in the thread where the allocation takes place.

If an allocation-tracking or promotion-tracking function returns `None`, memprof stops tracking the corresponding value.

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

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

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

Start the sampling with the given parameters. Fails if sampling is already active.

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

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.

Sampling is temporarily disabled when calling a callback for the current thread. So they do not need to be re-entrant if the program is single-threaded. However, if threads are
emulation of the fma is costly, make sure that you are using hardware fma support if
performance matters.

Since: 4.08

val rem : float -> float -> float

rem a b returns the remainder of a with respect to b. The returned value is a -. n *. b,
where n is the quotient a / b rounded towards zero to an integer.

val succ : float -> float

succ x returns the floating point number right after x i.e., the smallest floating-point number greater than x. See also `Float.next_after` [29.22].

Since: 4.08

val pred : float -> float

pred x returns the floating-point number right before x i.e., the greatest floating-point number smaller than x. See also `Float.next_after` [29.22].

Since: 4.08

val abs : float -> float

abs f returns the absolute value of f.

val infinity : float

Positive infinity.

val neg_infinity : float

Negative infinity.

val nan : float

A special floating-point value denoting the result of an undefined operation such as 0.0 / .
0.0. Stands for 'not a number'. Any floating-point operation with nan as argument returns
nan as result, unless otherwise specified in IEEE 754 standard. As for floating-point
comparisons, =, <, <=, > and >= return false and <> returns true if one or both of their
arguments is nan.

nan is quiet_nan since 5.1; it was a signaling NaN before.

val signaling_nan : float

Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be
useful for interoperability with C libraries.

Since: 5.1

val quiet_nan : float

Quiet NaN.

Since: 5.1
used, it is possible that a context switch occurs during a callback, in this case the
callback functions must be re-entrant.

Note that the callback can be postponed slightly after the actual event. The callstack
passed to the callback is always accurate, but the program state may have evolved.

val stop : unit -> unit

Stop the sampling. Fails if sampling is not active.

This function does not allocate memory.

All the already tracked blocks are discarded. If there are pending postponed callbacks,
they may be discarded.

Calling stop when a callback is running can lead to callbacks not being called even
though some events happened.

end

Memprof is a sampling engine for 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 callback 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.

## 28.24 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[28.24], Hashtbl.find_opt[28.24]) is normally very
fast, often faster than the equivalent lookup in Map[28.33].

The functors Hashtbl.Make[28.24] and Hashtbl.MakeSeeded[28.24] can be used when perfor-
mance 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 Hashtbl.t[28.24] hash table is useful in simpler cases or in interactive envi-
ronments. It uses the polymorphic Hashtbl.hash[28.24] 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].

**Alert** unsynchronized_access. Unsynchronized accesses to hash tables are a programming
error.
val pi : float

The constant pi.

val max_float : float

The largest positive finite value of type `float`.

val min_float : float

The smallest positive, non-zero, non-denormalized value of type `float`.

val epsilon : float

The difference between 1.0 and the smallest exactly representable floating-point number greater than 1.0.

val is_finite : float -> bool

`is_finite` x is true if and only if x is finite i.e., not infinite and not `Float.nan`[29.22].

Since: 4.08

val is_infinite : float -> bool

`is_infinite` x is true if and only if x is `Float POS infinity`[29.22] or `Float NEG infinity`[29.22].

Since: 4.08

val is_nan : float -> bool

`is_nan` x is true if and only if x is not a number (see `Float.nan`[29.22]).

Since: 4.08

val is_integer : float -> bool

`is_integer` x is true if and only if x is an integer.

Since: 4.08

val of_int : int -> float

Convert an integer to floating-point.

val to_int : float -> int

Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers.

val of_string : string -> float

Convert the given string to a `float`. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is `[-]dd.ddd (e|E) [+|-] dd`, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is `[-]0(x|X) hh.hhh (p|P) [+|-] dd`, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and
## 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[28.36]`).

## 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 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 (`Hashtbl.hash[28.24]`) 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[28.24]` 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[28.24]` or `Hashtbl.iter[28.24]` 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[28.24]` 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

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**
fractional parts must be given; the exponent part is optional. The _ (underscore) character
can appear anywhere in the string and is ignored. Depending on the execution platforms,
other representations of floating-point numbers can be accepted, but should not be relied
upon.

**Raises** Failure if the given string is not a valid representation of a float.

val of_string_opt : string -> float option

Same as of_string, but returns None instead of raising.

val to_string : float -> string

Return a string representation of a floating-point number.

This conversion can involve a loss of precision. For greater control over the manner in which
the number is printed, see `FORMAT[29.47]`.

This function is an alias for `string_of_float[28.2]`.

type fpclass = fpclass =

| FP_normal

Normal number, none of the below

| FP_subnormal

Number very close to 0.0, has reduced precision

| FP_zero

Number is 0.0 or -0.0

| FP_infinite

Number is positive or negative infinity

| FP_nan

Not a number: result of an undefined operation

The five classes of floating-point numbers, as determined by the
`Float.classify_float[29.22]` function.

val classify_float : float -> fpclass

Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number.

val pow : float -> float -> float

Exponentiation.

val sqrt : float -> float

Square root.

val cbrt : float -> float
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[28.24] 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[28.24]`.

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[28.24] tbl key` followed by `Hashtbl.add[28.24] tbl key data`.

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.
Cube root.

**Since: 4.13**

**val exp : float -> float**

Exponential.

**val exp2 : float -> float**

Base 2 exponential function.

**Since: 4.13**

**val log : float -> float**

Natural logarithm.

**val log10 : float -> float**

Base 10 logarithm.

**val log2 : float -> float**

Base 2 logarithm.

**Since: 4.13**

**val expm1 : float -> float**

expm1 x computes exp x -. 1.0, giving numerically-accurate results even if x is close to 0.0.

**val log1p : float -> float**

log1p x computes log(1.0 +. x) (natural logarithm), giving numerically-accurate results even if x is close to 0.0.

**val cos : float -> float**

Cosine. Argument is in radians.

**val sin : float -> float**

Sine. Argument is in radians.

**val tan : float -> float**

Tangent. Argument is in radians.

**val acos : float -> float**

Arc cosine. The argument must fall within the range [-1.0, 1.0]. Result is in radians and is between 0.0 and pi.

**val asin : float -> float**

Arc sine. The argument must fall within the range [-1.0, 1.0]. Result is in radians and is between -pi/2 and pi/2.
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 : ('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` [28.24] apply as well.

**Since: 4.03**

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.

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

After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: `Hashtbl.create` [28.24] 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 `Hashtbl.create` [28.24] 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` [28.24]. This is intentional.

Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`.

**Since: 4.00**
**val atan : float -> float**

Arc tangent. Result is in radians and is between -pi/2 and pi/2.

**val atan2 : float -> float -> float**

atan2 y x returns the arc tangent of y / x. The signs of x and y are used to determine the quadrant of the result. Result is in radians and is between -pi and pi.

**val hypot : float -> float -> float**

hypot x y returns sqrt(x * x + y * y), that is, the length of the hypotenuse of a right-angled triangle with sides of length x and y, or, equivalently, the distance of the point (x,y) to origin. If one of x or y is infinite, returns infinity even if the other is nan.

**val cosh : float -> float**

Hyperbolic cosine. Argument is in radians.

**val sinh : float -> float**

Hyperbolic sine. Argument is in radians.

**val tanh : float -> float**

Hyperbolic tangent. Argument is in radians.

**val acosh : float -> float**

Hyperbolic arc cosine. The argument must fall within the range [1.0, inf]. Result is in radians and is between 0.0 and inf.

**Since:** 4.13

**val asinh : float -> float**

Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians.

**Since:** 4.13

**val atanh : float -> float**

Hyperbolic arc tangent. The argument must fall within the range [-1.0, 1.0]. Result is in radians and ranges over the entire real line.

**Since:** 4.13

**val erf : float -> float**

Error function. The argument ranges over the entire real line. The result is always within [-1.0, 1.0].

**Since:** 4.13

**val erfc : float -> float**
```h
val is_randomized: unit -> bool
```

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

**Since: 4.03**

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

Return a copy of the given hashtable. Unlike `Hashtbl.copy[28.24]`, `Hashtbl.rebuild[28.24]` h 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[28.24]` for more information.

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

**Since: 4.12**

```h
type statistics =
{
    num bindings: int;

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

```h
num buckets: int;

    Number of buckets in the table.
```

```h
max bucket length: int;

    Maximal number of bindings per bucket.
```

```h
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.
```

```h
}
```

**Since: 4.00**

```h
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

```h
val to_seq: ('a, 'b) t -> ('a * 'b) Seq.t
```
Complementary error function ($erfc x = 1 - erf x$). The argument ranges over the entire real line. The result is always within $[0.0, 2.0]$.

**Since:** 4.13

**val trunc : float -> float**

trunc x rounds x to the nearest integer whose absolute value is less than or equal to x.

**Since:** 4.08

**val round : float -> float**

round x rounds x to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If x is an integer, $+0., -0., nan$, or infinite, x itself is returned.

On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform.

**Since:** 4.08

**val ceil : float -> float**

Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float.

**val floor : float -> float**

Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float.

**val next_after : float -> float -> float**

next_after x y returns the next representable floating-point value following x in the direction of y. More precisely, if y is greater (resp. less) than x, it returns the smallest (resp. largest) representable number greater (resp. less) than x. If x equals y, the function returns y. If x or y is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If x is the smallest denormalized positive number, `next_after x 0. = 0`.

**Since:** 4.08

**val copy_sign : float -> float -> float**

copy_sign x y returns a float whose absolute value is that of x and whose sign is that of y. If x is `nan`, returns `nan`. If y is `nan`, returns either x or -. x, but it is not specified which.

**val sign_bit : float -> bool**

sign_bit x is true if and only if the sign bit of x is set. For example `sign_bit 1.` and `signBit 0.` are false while `sign_bit (-1.)` and `sign_bit (-0.)` are true.

**Since:** 4.08

**val frexp : float -> float * int**
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

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

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

**Since:** 4.07

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

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

**Since:** 4.07

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

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

**Since:** 4.07

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

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

**Since:** 4.07

```hkl
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[28.24]`, which means that if two pairs have the same key, only the latest one will appear in the table.

**Since:** 4.07

## Functional 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
```
`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x * .2 ** n` and `0.5 <= x < 1.0`.

`val ldexp : float -> int -> float`

`ldexp x n` returns `x * .2 ** n`.

`val modf : float -> float * float`

`modf f` returns the pair of the fractional and integral part of `f`.

`type t = float`

An alias for the type of floating-point numbers.

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

`compare x y` returns 0 if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation.

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

The equal function for floating-point numbers, compared using `Float comparisons` [29.22].

`val min : t -> t -> t`

`min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.`

Since: 4.08

`val max : float -> float -> float`

`max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.`

Since: 4.08

`val min_max : float -> float -> float * float`

`min_max x y` is `(min x y, max x y)`, just more efficient.

Since: 4.08

`val min_num : t -> t -> t`

`min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.`

Since: 4.08

`val max_num : t -> t -> t`

`max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.`

Since: 4.08
```kotlin
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`.

```kotlin
module type HashedType =
sig
    type t
```

The type of the hashtable keys.

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

The equality predicate used to compare keys.

```kotlin
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[28.24])` for comparing objects by structure (provided objects do not contain floats)

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

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

```kotlin
end
```

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

```kotlin
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
```rust
val min_max_num : float -> float -> float * float
```

`min_max_num x y` is (`min_num x y`, `max_num x y`), just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`.

**Since:** 4.08

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

A seeded hash function for floats, 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

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

An unseeded hash function for floats, 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]`.

```python
module Array :
```

```c
sig
```

```c
type t = floatarray
```

The type of float arrays with packed representation.

**Since:** 4.08

```rust
val length : t -> int
```

Return the length (number of elements) of the given floatarray.

```rust
val get : t -> int -> float
```

`get` n returns the element number n of floatarray a.

**Raises:** `Invalid_argument` if n is outside the range 0 to (length a - 1).

```rust
val set : t -> int -> float -> unit
```

`set` n x modifies floatarray a in place, replacing element number n with x.

**Raises:** `Invalid_argument` if n is outside the range 0 to (length a - 1).

```rust
val make : int -> float -> t
```

`make` n x returns a fresh floatarray of length n, initialized with x.

**Raises:** `Invalid_argument` if n < 0 or n > Sys.maxFloatarray_length.

```rust
val create : int -> t
```

`create` n returns a fresh floatarray of length n, with uninitialized data.

**Raises:** `Invalid_argument` if n < 0 or n > Sys.maxFloatarray_length.
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

end

The output signature of the functor Hashtbl.Make[28.24].
```h
val init : int -> (int -> float) -> t
```

`init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers 0 to `n-1`.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.maxFloatarray_length`.

```h
val make_matrix : int -> int -> float -> t array
```

`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where all elements are initialized with `e`.

**Since:** 5.2

**Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than `Sys.maxFloatarray_length` [29.60].

```h
val init_matrix : int -> int -> (int -> int -> float) -> t array
```

`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index `(x,y)` is initialized with `f x y`.

**Since:** 5.2

**Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than `Sys.maxFloatarray_length` [29.60].

```h
val append : t -> t -> t
```

`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`.

**Raises** `Invalid_argument` if `length v1 + length v2 > Sys.maxFloatarray_length`.

```h
val concat : t list -> t
```

Same as `Float Array.append` [29.22], but concatenates a list of floatarrays.

```h
val sub : t -> int -> int -> t
```

`sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.

```h
val copy : t -> t
```

`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`.

```h
val fill : t -> int -> int -> float -> unit
```
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[28.24]` below.

end

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

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

Since: 4.05
fill a `pos` `len` `x` modifies the `floatarray` `a` in place, storing `x` in elements number `pos` to `pos` + `len` - 1.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.

`val blit: t -> int -> t -> int -> int -> unit`

`blit src src_pos dst dst_pos len` copies `len` elements from `floatarray src`, starting at element number `src_pos`, to `floatarray dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same `floatarray`, and the source and destination chunks overlap.

**Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.

`val to_list: t -> float list`

`to_list` `a` returns the list of all the elements of `a`.

`val of_list: float list -> t`

`of_list` `l` returns a fresh `floatarray` containing the elements of `l`.

**Raises** `Invalid_argument` if the length of `l` is greater than `Sys.maxFloatarray_length`.

## Comparison

`val equal: (float -> float -> bool) -> t -> t -> bool`

`equal` `eq a b` is true if and only if `a` and `b` have the same length `n` and for all `i` in `[0;n-1]`, `eq a.(i) b.(i)` is true.

**Since:** 5.4

`val compare: (float -> float -> int) -> t -> t -> int`

`compare cmp a b` compares `a` and `b` according to the shortlex order, that is, shorter arrays are smaller and equal-sized arrays are compared in lexicographic order using `cmp` to compare elements.

**Since:** 5.4

## Iterators

`val iter: (float -> unit) -> t -> unit`

`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`.

`val iteri: (int -> float -> unit) -> t -> unit`
```hkl
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[28.24]`.

Since: 4.00

module MakeSeeded :

functor (H : SeededHashedType) -> SeededS with type key = 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 `Hashtbl.randomize[28.24]`).

Since: 4.00
Same as `Float Array iter` [29.22], but the function is applied with the index of the element as first argument, and the element itself as second argument.

`val map : (float -> float) -> t -> t`

`map` f a applies function f to all the elements of a, and builds a `floatarray` with the results returned by f.

`val map_inplace : (float -> float) -> t -> unit`

`map_inplace` f a applies function f to all elements of a, and updates their values in place.

**Since:** 5.1

`val mapi : (int -> float -> float) -> t -> t`

Same as `Float Array.map` [29.22], but the function is applied to the index of the element as first argument, and the element itself as second argument.

`val mapi_inplace : (int -> float -> float) -> t -> unit`

Same as `Float Array.map_inplace` [29.22], but the function is applied to the index of the element as first argument, and the element itself as second argument.

**Since:** 5.1

`val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc`

`fold_left` f x init computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1), where n is the length of the `floatarray` init.

`val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc`

`fold_right` f a init computes f a.(0) (f a.(1) (... (f a.(n-1) init) ...)), where n is the length of the `floatarray` a.

## Iterators on two arrays

`val iter2 : (float -> float -> unit) -> t -> t -> unit`

`Array.iter2` f a b applies function f to all the elements of a and b.

**Raises** `Invalid_argument` if the `floatarrays` are not the same size.

`val map2 : (float -> float -> float) -> t -> t -> t`

`map2` f a b applies function f to all the elements of a and b, and builds a `floatarray` with the results returned by f: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.

**Raises** `Invalid_argument` if the `floatarrays` are not the same size.
## 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 comparisons 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` [28.24] 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` [28.24] and `Hashtbl.seeded_hash` [28.24] take `meaningful = 10` and `total = 100`.

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

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

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

**Since:** 4.00

## Examples

### Basic Example

```hkl
(* 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>
```
## Array scanning

`val for_all : (float -> bool) -> t -> bool`

`for_all f [|a1; ...; an|]` checks if all elements of the `floatarray` satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.

`val exists : (float -> bool) -> t -> bool`

`exists f [|a1; ...; an|]` checks if at least one element of the `floatarray` satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.

`val mem : float -> t -> bool`

`mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`.

`val mem_ieee : float -> t -> bool`

Same as `Floatola`. `Array.mem[29.22]`, but uses IEEE equality instead of structural equality.

## Array searching

`val find_opt : (float -> bool) -> t -> float option`

`val find_index : (float -> bool) -> t -> int option`

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

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

**Since: 5.1**

`val find_map : (float -> 'a option) -> t -> 'a option`

`val find_mapi : (int -> float -> 'a option) -> t -> 'a 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**

## Sorting and shuffling

`val sort : (float -> float -> int) -> t -> unit`

Sort a `floatarray` 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 below for a complete specification). For example, `compare[28.2]` is a suitable comparison function.
```perl
# 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[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`.

```perl
# 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;
```
After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.

The current implementation uses Heap Sort. It runs in constant stack space.

Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a`:

* `cmp x y > 0` if and only if `cmp y x < 0`

* if `cmp x y ≥ 0` and `cmp y z ≥ 0` then `cmp x z ≥ 0`

When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all `i` and `j` valid indices of `a`:

* `cmp a.(i) a.(j) ≥ 0` if `i ≥ j`

**val stable_sort : (float -> float -> int) -> t -> unit**

Same as `Float Array.sort` [29.22], but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.

The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of `Float Array.sort` [29.22].

**val fast_sort : (float -> float -> int) -> t -> unit**

Same as `Float Array.sort` [29.22] or `Float Array.stable_sort` [29.22], whichever is faster on typical input.

**val shuffle : rand:(int -> int) -> t -> unit**

`shuffle rand a` randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform.

`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range `[0;n-1]`. `Random.int` [29.49] can be used for this (do not forget to initialize [29.49] the generator).

**Since: 5.2**

## Float arrays and Sequences

**val to_seq : t -> float Seq.t**

Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.

**val to_seqi : t -> (int * float) Seq.t**

Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.
(* 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 cycle (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)]

## 28.25 Module In_channel: Input channels.

This module provides functions for working with input channels.
See the example section[28.44] below.
**Since:** 4.14

### Channels

type t = in_channel

The type of input channel.

type open_flag = open_flag =
| Open_rdonly
  open for reading.
| Open_wronly
```h
val of_seq : float Seq.t -> t
```

Create an array from the generator.

```h
val map_to_array : (float -> 'a) -> t -> 'a array
```

map_to_array f a applies function f to all the elements of a, and builds an array with the results returned by f: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.

```h
val map_from_array : ('a -> float) -> 'a array -> t
```

map_from_array f a applies function f to all the elements of a, and builds a floatarray with the results returned by f.

## Arrays and concurrency safety

Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.

## Atomicity

Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.

For example, consider the following program:

```h
let size = 100_000_000
let a = Float Array.make size 1.
let update a f () =
  Float Array.iteri (fun i x -> Float Array.set a i (f x)) a
let d1 = Domain spawn (update a (fun x -> x +. 1.))
let d2 = Domain spawn (update a (fun x -> 2. *. x +. 1.))
let () = Domain.join d1; Domain.join d2
```

After executing this code, each field of the float array a is either 2., 3., 4. or 5.. If atomicity is required, then the user must implement their own synchronization (for example, using `Mutex.t[29.38]`).

## Data races

If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.

A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races,
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[28.25].

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[28.25], 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[28.25].

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

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[28.25] and In_channel.open_bin[28.25] 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
the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.

Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.

Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.

## Tearing

Float arrays have two supplementary caveats in the presence of data races.

First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.

For instance, at the end of

```javascript
let zeros = Float Array.make size 0.
let max_floats = Float Array.make size Float.max_float
let res = Float Array.copy zeros
let d1 = Domain spawn (fun () -> Float Array.blit zeros 0 res 0 size)
let d2 = Domain spawn (fun () -> Float Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```

the `res` float array might contain values that are neither 0. nor `max_float`.

Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.

end

Float arrays with packed representation.

module ArrayLabels :

sig

type t = floatarray

The type of float arrays with packed representation.

Since: 4.08

val length : t -> int

Return the length (number of elements) of the given floatarray.

val get : t -> int -> float
Like `In_channel.with_open_bin[28.25]`, but the channel is opened in text mode (see `In_channel.open_text[28.25]`).

`val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a`

Like `In_channel.with_open_bin[28.25]`, but can specify the opening mode and file permission, in case the file must be created (see `In_channel.open_gen[28.25]`).

`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[28.25]`, which does nothing when applied to an already closed channel.

`val close_noerr : t -> unit`

Same as `In_channel.close[28.25]`, 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 inputbyte : t -> int option`

Same as `In_channel.input_char[28.25]`, 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[28.55]` is `true` in which case it is the sequence of characters `\r\n`.

`val really_input_string : t -> int -> string option`

`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.
get a n returns the element number n of floatarray a.

Raises Invalid_argument if n is outside the range 0 to (length a - 1).

val set : t -> int -> float -> unit

set a n x modifies floatarray a in place, replacing element number n with x.

Raises Invalid_argument if n is outside the range 0 to (length a - 1).

val make : int -> float -> t

make n x returns a fresh floatarray of length n, initialized with x.

Raises Invalid_argument if n < 0 or n > Sys.max_floatarray_length.

val create : int -> t

create n returns a fresh floatarray of length n, with uninitialized data.

Raises Invalid_argument if n < 0 or n > Sys.max_floatarray_length.

val init : int -> f:(int -> float) -> t

init n ~f returns a fresh floatarray of length n, with element number i initialized to
the result of f i. In other terms, init n ~f tabulates the results of f applied to the
integers 0 to n-1.

Raises Invalid_argument if n < 0 or n > Sys.max_floatarray_length.

val make_matrix : dimx:int -> dimy:int -> float -> t array

make_matrix ~dimx ~dimy e returns a two-dimensional array (an array of arrays) with
first dimension dimx and second dimension dimy, where all elements are initialized with
e.

Since: 5.2

Raises Invalid_argument if dimx or dimy is negative or greater than
Sys.max_floatarray_length[29.60].

val init_matrix : dimx:int -> dimy:int -> f:(int -> int -> float) -> t array

init_matrix ~dimx ~dimy ~f returns a two-dimensional array (an array of arrays)
with first dimension dimx and second dimension dimy, where the element at index (x,y)
is initialized with f x y.

Since: 5.2

Raises Invalid_argument if dimx or dimy is negative or greater than
Sys.max_floatarray_length[29.60].

val append : t -> t -> t

append v1 v2 returns a fresh floatarray containing the concatenation of the floatarrays
v1 and v2.

Raises Invalid_argument if length v1 + length v2 > Sys.max_floatarray_length.
val `input_lines`: `t -> string list`

`input_lines` `ic` reads lines using `In_channel.input_line` [28.25] 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` [28.25] to read exactly `len` characters.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.

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`.

val `fold_lines`: `('acc -> string -> 'acc) -> 'acc -> t -> 'acc`

`fold_lines` `f` `init` `ic` reads lines from `ic` using `In_channel.input_line` [28.25] 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

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.

val `pos`: `t -> int64`
`val concat : t list -> t`

Same as `Float.arrayLabels.append[29.22]`, but concatenates a list of floatarrays.

`val sub : t -> pos:int -> len:int -> t`

`sub a ~pos ~len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`; that is, if `pos < 0`, or `len < 0`, or `pos + len > length a`.

`val copy : t -> t`

`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`.

`val fill : t -> pos:int -> len:int -> float -> unit`

`fill a ~pos ~len` x modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid subarray of `a`.

`val blit : src:t ->`

`src_pos:int -> dst:t -> dst_pos:int -> len:int -> unit`

`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap.

**Raises** `Invalid_argument` if `src_pos` and `len` do not designate a valid subarray of `src`, or if `dst_pos` and `len` do not designate a valid subarray of `dst`.

`val to_list : t -> float list`

`to_list` a returns the list of all the elements of `a`.

`val of_list : float list -> t`

`of_list l` returns a fresh floatarray containing the elements of `l`.

**Raises** `Invalid_argument` if the length of `l` is greater than `Sys.maxFloatarray_length`.

## Comparison

`val equal : eq:(float -> float -> bool) ->`

`t -> t -> bool`

`equal eq a b` is true if and only if `a` and `b` have the same length `n` and for all `i` in `[0:n-1]`, `eq a.(i) b.(i)` is true.

**Since:** 5.4
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` [28.25], then going back to this position using `In_channel.seek` [28.25] 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. 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.

**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`.

This function has no effect under operating systems that do not distinguish between text mode and binary mode.

**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:

```hml
let read_file file = In_channel.with_open_bin file In_channel.input_all
```

Reading a line from stdin:

```hml
let user_input () = In_channel.input_line In_channel.stdin
```

## 28.26 Module Int : Integer values.

Integers are `Sys.int_size` [28.55] bits wide and use two's complement representation. All operations are taken modulo $2^{\text{Sys.int_size}}$. They do not fail on overflow.

**Since:** 4.08
```hkl
val compare : cmp:(float -> float -> int) ->
    t -> t -> int
```

compare cmp a b compares a and b according to the shortlex order, that is, shorter arrays are smaller and equal-sized arrays are compared in lexicographic order using cmp to compare elements.

**Since: 5.4**

## Iterators

```hkl
val iter : f:(float -> unit) -> t -> unit
```

iter ~f a applies function f in turn to all the elements of a. It is equivalent to f
a.(0); f a.(1); ...; f a.(length a - 1); ().

```hkl
val iteri : f:(int -> float -> unit) -> t -> unit
```

Same as `Floatola陣 labels`. `iter` [29.22], but the function is applied with the index of the element as first argument, and the element itself as second argument.

```hkl
val map : f:(float -> float) -> t -> t
```

map ~f a applies function f to all the elements of a, and builds a floatarray with the
results returned by f.

```hkl
val map_inplace : f:(float -> float) -> t -> unit
```

map_inplace f a applies function f to all elements of a, and updates their values in
place.

**Since: 5.1**

```hkl
val mapi : f:(int -> float -> float) -> t -> t
```

Same as `Floatola陣 labels`. `map` [29.22], but the function is applied to the index of the element as first argument, and the element itself as second argument.

```hkl
val mapi_inplace : f:(int -> float -> float) -> t -> unit
```

Same as `Floatola陣 labels`. `map_inplace` [29.22], but the function is applied to the index of the element as first argument, and the element itself as second argument.

**Since: 5.1**

```hkl
val fold_left : f:'acc -> float -> 'acc) -> init:'acc -> t -> 'acc
```

fold_left ~f x ~init computes f (... (f (f x init.(0)) init.(1)) ...) init.(n-1), where n is the length of the floatarray init.

```hkl
val fold_right : f:(float -> 'acc -> 'acc) -> t -> init:'acc -> 'acc
```

fold_right f a init computes f a.(0) (f a.(1) (... (f a.(n-1) init) ...)), where n is the length of the floatarray a.
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.

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 (/) [27.2] for details.

val rem : int -> int -> int

rem x y is the remainder x mod y. See (mod) [27.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 [28.26].

val max_int : int

max_int is the greatest representable integer, 2{^[Sys.int_size - 1]} - 1.
## Iterators on two arrays

```hkl
val iter2 : f:(float -> float -> unit) ->
    t -> t -> unit
```

`Array.iter2 ~f a b` applies function `f` to all the elements of `a` and `b`.

**Raises** `Invalid_argument` if the floatarrays are not the same size.

```hkl
val map2 : f:(float -> float -> float) ->
    t -> t -> t
```

`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`.

**Raises** `Invalid_argument` if the floatarrays are not the same size.

## Array scanning

```hkl
val for_all : f:(float -> bool) -> t -> bool
```

`for_all ~f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.

```hkl
val exists : f:(float -> bool) -> t -> bool
```

`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.

```hkl
val mem : float -> set:t -> bool
```

`mem a ~set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`.

```hkl
val mem_ieee : float -> set:t -> bool
```

Same as `Float ArrayLabels.mem` [29.22], but uses IEEE equality instead of structural equality.

## Array searching

```hkl
val find_opt : f:(float -> bool) -> t -> float option
```

```hkl
val find_index : f:(float -> bool) -> t -> int option
```

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

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

**Since:** 5.1
val min_int : int
min_int is the smallest representable integer, -2{~[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
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[28.55].

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[28.55].

val shift_right logical : int -> int -> int
shift_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[28.55].

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[27.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
```hkl
val find_map : f:(float -> 'a option) -> t -> 'a option
```

```hkl
val find_mapi : f:(int -> float -> 'a option) -> t -> 'a 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**

## Sorting and shuffling

```hkl
val sort : cmp:(float -> float -> int) -> t -> unit
```

Sort a floatarray 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 below for a complete specification). For example, `compare[28.2]` is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space.

The current implementation uses Heap Sort. It runs in constant stack space.

Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a`:

* `cmp x y > 0` if and only if `cmp y x < 0`

* if `cmp x y ≥ 0` and `cmp y z ≥ 0` then `cmp x z ≥ 0`

When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all `i` and `j` valid indices of `a`:

* `cmp a.(i) a.(j) ≥ 0` if `i ≥ j`

```hkl
val stable_sort : cmp:(float -> float -> int) -> t -> unit
```

Same as `Floatola`. `ArrayLabels.sort[29.22]`, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space.

The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of `Floatola`. `ArrayLabels.sort[29.22]`.

```hkl
val fast_sort : cmp:(float -> float -> int) -> t -> unit
```

Same as `Floatola`. `ArrayLabels.sort[29.22]` or `Floatola`. `ArrayLabels.stable_sort[29.22]`, whichever is faster on typical input.

```hkl
val shuffle : rand:(int -> int) -> t -> unit
```

`shuffle ~rand` a randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform.
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

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[28.24]`. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded[28.24]`.

Since: 5.1

val hash : int -> int

An unseeded hash function for 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.27 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 1:

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.
`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range `[0;n-1]`. `Random.int[29.49]` can be used for this (do not forget to initialize[29.49] the generator).

**Since: 5.2**

## Float arrays and Sequences

`val to_seq : t -> float Seq.t`

Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence.

`val to_seqi : t -> (int * float) Seq.t`

Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence.

`val of_seq : float Seq.t -> t`

Create an array from the generator.

`val map_to_array : f:(float -> 'a) -> t -> 'a array`

`map_to_array ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f: [| f a.(0); f a.(1); ...; f a.(length a - 1) |]`.

`val map_from_array : f:'a -> float -> 'a array -> t`

`map_from_array ~f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`.

## Arrays and concurrency safety

Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results.

## Atomicity

Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays.

For example, consider the following program:

```hkl
let size = 100_000_000
let a = Float.arrayLabels.make size 1.
let update a f () =
```
val minus_one : int32

The 32-bit integer -1.

val neg : int32 -> int32

Unary negation.

val add : int32 -> int32 -> int32

Addition.

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 `/` [27.2].

**Raises** `Division_by_zero` if the second argument is zero.

val unsigned_div : int32 -> int32 -> int32

Same as `Int32.div` [28.27], 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` [28.27], 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. `Int32eelrem` 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.
```kotlin
Float ArrayLabels.iteri ~f: (fun i x -> Float Array.set a i (f x)) a
let d1 = Domain spawn (update a (fun x -> x +. 1.))
let d2 = Domain spawn (update a (fun x -> 2. *. x +. 1.))
let () = Domain.join d1; Domain.join d2
```

After executing this code, each field of the float array `a` is either 2., 3., 4. or 5.. If atomicity is required, then the user must implement their own synchronization (for example, using `Mutex.t[29.38]`).

## Data races

If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains.

A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains.

Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements.

Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions.

## Tearing

Float arrays have two supplementary caveats in the presence of data races.

First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution.

For instance, at the end of

```kotlin
let zeros = Floatwel Array.make size 0.
let max_floats = Floatwel Array.make size Float.max_float
let res = Floatwel Array.copy zeros
let d1 = Domain spawn (fun () -> Floatwel Array.blit zeros 0 res 0 size)
let d2 = Domain spawn (fun () -> Floatwel Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```

the `res` float array might contain values that are neither 0. nor `max_float`.

Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation.
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.

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_right: 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[28.27], 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
end

Float arrays with packed representation (labeled functions).

## 29.23 Module Format : Pretty-printing.

If you are new to this module, see the examples[29.48] below.

This module implements a pretty-printing facility to format values within 'pretty-printing boxes'[29.23] and 'semantic tags'[29.23] combined with a set of printf-like functions[29.23]. The pretty-printer splits lines at specified break hints[29.23], and indents lines according to the box structure. Similarly, semantic tags[29.23] can be used to decouple text presentation from its contents.

This pretty-printing facility is implemented as an overlay on top of abstract formatters[29.23] which provide basic output functions. Some formatters are predefined, notably:

* `Format.std_formatter[29.23]` outputs to stdout[28.2]

* `Format.err_formatter[29.23]` outputs to stderr[28.2]

Most functions in the `Format[29.23]` module come in two variants: a short version that operates on the current domain's standard formatter as obtained using `Format.get_std_formatter[29.23]` and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to `Format.get_std_formatter[29.23]` is delayed until the last argument is received.

More formatters can be created with `Format formatter of out_channel[29.23]`, `Format formatter of buffer[29.23]`, `Format formatter of symbolic output buffer[29.23]` or using custom formatters[29.23].

**Warning:** Since formatters[29.23] contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization. This may result in `Invalidargument` being raised or an unspecified behavior.

If multiple domains write to the same output channel using the predefined formatters (as obtained by `Format.get_std_formatter[29.23]` or `Format.get_err_formatter[29.23]`), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with `Format.print_flush[29.23]`. This synchronization is not performed by formatters obtained from `Format formatter of out_channel[29.23]` (on the standard out channels or others).

## Introduction

You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function `Format.fprintf[29.23]`.

You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings.
### `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[28.27], Int32.max_int[28.27]]`, no exception is raised, and an unspecified, platform-dependent integer is returned.

### `val to_float`: `int32` -> `float`

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[28.27]` 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[27.2]`. Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors `Set.Make[28.49]` and `Map.Make[28.33]`.
For instance, the sequence `open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`.

Rule of thumb for casual users of this library:

* use simple pretty-printing boxes (as obtained by `open_box 0`);

* use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint;

* once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`);

* when the material for a pretty-printing box has been printed, call `close_box ()` to close the box;

* at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`.

The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly.

In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer.

**Warning:** mixing calls to pretty-printing functions of this module with calls to `Stdlib[28.2]` low level output functions is error prone.

The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, `Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT";` leads to output `<>PRETTYTEXT`.

## Formatters

### type formatter

Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [29.23].

## Pretty-printing boxes

The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer.

Each different pretty-printing box kind introduces a specific line splitting policy:
`val unsigned_compare : t -> t -> int`

Same as `Int32 compare` [28.27], except that arguments are interpreted as unsigned 32-bit integers.

**Since:** 4.08

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

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` [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 32-bit 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.28 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`
* within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper),

* within a *vertical* box, break hints always split the line,

* within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line,

* within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line.

Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line.

Moreover, opening a box after the maximum indentation limit [29.23] splits the line whether or not the box would end up fitting on the line.

```k language="k language="k language="k language="k
val pp_open_box : formatter -> int -> unit
```

```k language="k language="k language="k language="k language="k
val open_box : int -> unit
```

`pp_open_box` ppf d opens a new compacting pretty-printing box with offset d in the formatter ppf.

Within this box, the pretty-printer prints as much as possible material on every line.

A break hint splits the line if there is no more room on the line to print the remainder of the box.

Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting “moves to the left” (i.e. the new line gets an indentation smaller than the one of the current line).

This box is the general purpose pretty-printing box.

If the pretty-printer splits the line in the box, offset d is added to the current indentation.

```k language="k language="k language="k language="k language="k
val pp_close_box : formatter -> unit -> unit
```

```k language="k language="k language="k language="k language="k
val close_box : unit -> unit
```

Closes the most recently open pretty-printing box.

```k language="k language="k language="k language="k language="k
val pp_open_hbox : formatter -> unit -> unit
```

```k language="k language="k language="k language="k language="k
val open_hbox : unit -> unit
```

`pp_open_hbox` ppf () opens a new 'horizontal' pretty-printing box.

This box prints material on a single line.

Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper).

```k language="k language="k language="k language="k language="k
val pp_open_vbox : formatter -> int -> unit
```

```k language="k language="k language="k language="k language="k
val open_vbox : int -> unit
```
let m_one: int64 = -1L

val zero : int64

The 64-bit integer 0.

val one : int64

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 (//)[27.2].

val unsigned_div : int64 -> int64 -> int64

Same as Int64.div[28.28], 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 unsignedRem : int64 -> int64 -> int64

Same as Int64.rem[28.28], except that arguments and result are interpreted as unsigned 64-bit integers.

**Since:** 4.08
`pp_open_vbox` `ppf` `d` opens a new 'vertical' pretty-printing box with offset `d`.

This box prints material on as many lines as break hints in the box.

Every break hint in a vertical box splits the line.

If the pretty-printer splits the line in the box, `d` is added to the current indentation.

`val pp_open_hvbox : formatter -> int -> unit`

`val open_hvbox : int -> unit`

`pp_open_hvbox` `ppf` `d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`.

This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a
vertical box.

If the pretty-printer splits the line in the box, `d` is added to the current indentation.

`val pp_open_hovbox : formatter -> int -> unit`

`val open_hovbox : int -> unit`

`pp_open_hovbox` `ppf` `d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`.

This box prints material as much as possible on every line.

A break hint splits the line if there is no more room on the line to print the remainder of the box.

If the pretty-printer splits the line in the box, `d` is added to the current indentation.

## Formatting functions

`val pp_print_string : formatter -> string -> unit`

`val print_string : string -> unit`

`pp_print_string` `ppf` `s` prints `s` in the current pretty-printing box.

`val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit`

`val print_substring : pos:int -> len:int -> string -> unit`

`pp_print_substring` `~pos ~len` `ppf` `s` prints the substring of `s` that starts at position `pos` and stops at position `pos+len` in the current pretty-printing box.

**Since: 5.3**

`val pp_print_bytes : formatter -> bytes -> unit`

`val print_bytes : bytes -> unit`

`pp_print_bytes` `ppf` `b` prints `b` in the current pretty-printing box.

**Since: 4.13**

`val pp_print_as : formatter -> int -> string -> unit`

`val print_as : int -> string -> unit`
val succ : int64 -> int64
Successor. Int64.succ x is Int64.add x Int64.one.

val pred : int64 -> int64
Predecessor. Int64(pred x is Int64.sub x Int64.one.

val abs : int64 -> int64
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_logica... 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).
`pp_print_as` `ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`.

`val pp_print_substring_as :`

`pos:int -> len:int -> formatter -> int -> string -> unit`

`val print_substring_as : pos:int -> len:int -> int -> string -> unit`

`pp_print_substring_as` ~first ~len `ppf len_as s` prints the substring of `s` that starts at position `pos` and stop at position `pos+len` in the current pretty-printing box as if it were of length `len_as`.

**Since:** 5.1

`val pp_print_int : formatter -> int -> unit`

`val print_int : int -> unit`

Print an integer in the current pretty-printing box.

`val pp_print_float : formatter -> float -> unit`

`val print_float : float -> unit`

Print a floating point number in the current pretty-printing box.

`val pp_print_char : formatter -> char -> unit`

`val print_char : char -> unit`

Print a character in the current pretty-printing box.

`val pp_print_bool : formatter -> bool -> unit`

`val print_bool : bool -> unit`

Print a boolean in the current pretty-printing box.

`val pp_print_nothing : formatter -> unit -> unit`

Print nothing.

**Since:** 5.2

## Break hints

A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules.

Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items.

Simple break hints are:

* the 'space': output a space or split the line if appropriate,

* the 'cut': split the line if appropriate.
### `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

Same as `Int64.to_int[28.28]`, 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[28.28], Int64.max_int[28.28]]`, 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[28.28]` 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`.
Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, "output a space" simply means printing a space character (ASCII code 32) and "split the line" means printing a newline character (ASCII code 10).

```kotlin
val pp_print_space : formatter -> unit -> unit
```

```kotlin
val print_space : unit -> unit
```

```
pp_print_space ppf () emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space.
```

```
pp_print_space ppf () is equivalent to pp_print_break ppf 1 0.
```

```kotlin
val pp_print_cut : formatter -> unit -> unit
```

```kotlin
val print_cut : unit -> unit
```

```
pp_print_cut ppf () emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing.
```

```
pp_print_cut ppf () is equivalent to pp_print_break ppf 0 0.
```

```kotlin
val pp_print_break : formatter -> int -> int -> unit
```

```kotlin
val print_break : int -> int -> unit
```

```
pp_print_break ppf nspaces offset emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints nspaces spaces.
```

If the pretty-printer splits the line, offset is added to the current indentation.

```kotlin
val pp_print_custom_break :
  formatter ->
  fits:string * int * string -> breaks:string * int * string -> unit
```

```
pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4) emits a custom break hint: the pretty-printer may split the line at this point.
```

If it does not split the line, then the s1 is emitted, then n spaces, then s2.

If it splits the line, then it emits the s3 string, then an indent (according to the box rules), then an offset of m spaces, then the s4 string.

While n and m are handled by formatter_out_functions.out indent, the strings will be handled by formatter_out_functions.out string. This allows for a custom formatter that handles indentation distinctly, for example, outputs <br/> tags or &nbsp; entities.

The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list `[a; b; c]`, you might want to add a trailing semicolon when it is printed vertically:

```
[
a;
b;
c;
```
`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`

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[27.2]`. Along with the type `t`, this function `compare` allows the module `Int64` 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 `Int64 comparisons` [28.28], 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`
]

You can do this as follows:

```python
printf "@[<v 0>[@;<0 2>@[<v 0>a;@,b;@,c@]%t]@]\n"
(pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, ""))
```

Since: 4.08

```python
val pp_force_newline : formatter -> unit -> unit
```

```python
val force_newline : unit -> unit
```

Force a new line in the current pretty-printing box.

The pretty-printer must split the line at this point,

Not the normal way of pretty-printing, since imperative line splitting may interfere with
current line counters and box size calculation. Using break hints within an enclosing vertical
box is a better alternative.

```python
val pp_print_if_newline : formatter -> unit -> unit
```

```python
val print_if_newline : unit -> unit
```

Execute the next formatting command if the preceding line has just been split. Otherwise,
ignore the next formatting command.

## Pretty-printing termination

```python
val pp_print_flush : formatter -> unit -> unit
```

```python
val print_flush : unit -> unit
```

End of pretty-printing: resets the pretty-printer to initial state.

All open pretty-printing boxes are closed, all pending text is printed. In addition, the
pretty-printer low level output device is flushed to ensure that all pending text is really
displayed.

Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering.

Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing.

Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to `flush` [28.2] to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency.
A seeded hash function for 64-bit 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**

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

An unseeded hash function for 64-bit 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.29 Module Lazy: Deferred computations.

```rust
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 `lazy (pattern)` also computes the underlying expression and tries to bind it to `pattern`:

```hl
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
```
```hcl
val pp_print_newline : formatter -> unit -> unit
```

```hcl
val print_newline : unit -> unit
```

End of pretty-printing: resets the pretty-printer to initial state.

All open pretty-printing boxes are closed, all pending text is printed.

Equivalent to `Format.print_flush[29.23]` with a new line emitted on the pretty-printer low-level output device immediately before the device is flushed. See corresponding words of caution for `Format.print_flush[29.23]`.

Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box.

## Margin

```hcl
val pp_infinity : int
```

`pp_infinity` is the maximal size of the margin. Its exact value is implementation dependent but is guaranteed to be greater than $10^9$.

Since: 5.2

```hcl
val pp_setmargin : formatter -> int -> unit
```

```hcl
val setmargin : int -> unit
```

`pp_setmargin` `ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d >= Format.pp_infinity[29.23]`, the right margin is set to `Format.pp_infinity[29.23] - 1`. If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`.

See also `Format.pp_set_geometry[29.23]`.

```hcl
val pp_getmargin : formatter -> unit -> int
```

```hcl
val getmargin : unit -> int
```

Returns the position of the right margin.

## Maximum indentation limit

```hcl
val pp_set_max indent : formatter -> int -> unit
```

```hcl
val set_max indent : int -> unit
```

`pp_set_max indent` `ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration,

```c
setmargin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@."
```
Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or
when the suspension tries to force itself recursively.

val force : 'a t -> 'a

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[28.29]).

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
yields

123456

789A

because the nested box "[@[7@]" is opened after the maximum indentation limit (7>5)
and its parent box does not fit on the current line. Either decreasing the length of the
parent box to make it fit on a line:

printf "[@123456[@7@]89@]@."

or opening an intermediary box before the maximum indentation limit which fits on the
current line

printf "[@123[@456[@7@]89@]A@]@."

avoids the rejection to the left of the inner boxes and print respectively "123456789" and "123456789A". Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid.

Nothing happens if `d` is smaller than 2.

If `d` is greater than the current margin, it is ignored, and the current maximum indentation limit is kept.

See also `Format.pp_set_geometry[29.23]`.

val pp_get_maxident : formatter -> unit -> int

val get_maxident : unit -> int

Return the maximum indentation limit (in characters).

Geometry

Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maximum indentation limit.

type geometry =

{ max ident : int ;
margin : int ;
}

Since: 4.08

val check_geometry : geometry -> bool

Check if the formatter geometry is valid: 1 < max ident < margin <
Format.pp_infinity[29.23]

Since: 4.08
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

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

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[28.29].

Raises

* Undefined if the forcing of x tries to force x itself recursively.

* Undefined (see Lazy. Undefined [28.29]).

28.30 Module Lexing : The run-time library for lexers generated
by ocamllex.

Positions

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.

val dummy_pos : position

A value of type *position*, guaranteed to be different from any valid *position*.
val pp_set_geometry : formatter -> max_indent: int -> margin: int -> unit

val set_geometry : max_indent: int -> margin: int -> unit

val pp_safe_set_geometry : formatter -> max_indent: int -> margin: int -> unit

val safe_set_geometry : max_indent: int -> margin: int -> unit

pp_set_geometry ppf ~maxident ~margin sets both the margin and maximum
indentation limit for ppf.

When 1 < maxident < margin < Format.pp_infinity[29.23], pp_set_geometry ppf
~maxident ~margin is equivalent to pp_setmargin ppf margin; pp_set_maxident
ppf maxident; and avoids the subtly incorrect pp_set_maxindent ppf maxindent;
pp_setmargin ppf margin;

Outside of this domain, pp_set_geometry raises an invalid argument exception whereas
pp_safe_set_geometry does nothing.

Since: 4.08

val pp_update_geometry : formatter -> (geometry -> geometry) -> unit

pp_update_geometry ppf (fun geo -> { geo with ... }) lets you update a formatter's
geometry in a way that is robust to extension of the geometry record with new fields.

Raises an invalid argument exception if the returned geometry does not satisfy
Format.check_geometry[29.23].

Since: 4.11

val update_geometry : (geometry -> geometry) -> unit

val pp_get_geometry : formatter -> unit -> geometry

val get_geometry : unit -> geometry

Return the current geometry of the formatter

Since: 4.08

Maximum formatting depth

The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously
open.

Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned
by Format.get_ellipse_text[29.23]()).

val pp_set_max boxes : formatter -> int -> unit

val set_max boxes : int -> unit

pp_set_max boxes ppf max sets the maximum number of pretty-printing boxes
simultaneously open.

Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text
returned by Format.get_ellipse_text[29.23]()).

Nothing happens if max is smaller than 2.
## Token buffer buffers

```c
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 inchan` 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 pp_get_max boxes : formatter -> unit -> int

val get_max boxes : unit -> int

Returns the maximum number of pretty-printing boxes allowed before ellipsis.

val pp_over_max boxes : formatter -> unit -> bool

val over_max boxes : unit -> bool

Tests if the maximum number of pretty-printing boxes allowed have already been opened.

Tabulation boxes

A tabulation box prints material on lines divided into cells of fixed length. A tabulation box provides
a simple way to display vertical columns of left adjusted text.

This box features command `set_tab` to define cell boundaries, and command `print_tab` to
move from cell to cell and split the line when there is no more cells to print on the line.

Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation
box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns
within module `Format` [29.23].

val pp_open_tbox : formatter -> unit -> unit

val open_tbox : unit -> unit

`open_tbox()` opens a new tabulation box.

This box prints lines separated into cells of fixed width.

Inside a tabulation box, special tabulation markers defines points of interest on the line (for
instance to delimit cell boundaries). Function `Format.set_tab` [29.23] sets a tabulation
marker at insertion point.

A tabulation box features specific tabulation breaks to move to next tabulation marker or split
the line. Function `Format.print_tbreak` [29.23] prints a tabulation break.

val pp_close_tbox : formatter -> unit -> unit

val close_tbox : unit -> unit

Closes the most recently opened tabulation box.

val pp_set_tab : formatter -> unit -> unit

val set_tab : unit -> unit

Sets a tabulation marker at current insertion point.

val pp_print_tab : formatter -> unit -> unit

val print_tab : unit -> unit

`print_tab()` emits a 'next' tabulation break hint: if not already set on a tabulation marker,
the insertion point moves to the first tabulation marker on the right, or the pretty-printer
splits the line and insertion point moves to the leftmost tabulation marker.

It is equivalent to `print_tbreak 0 0`.
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[28.30]` 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` and `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**
```rust
val pp_print_tbreak: formatter -> int -> int -> unit
```

```rust
val print_tbreak: int -> int -> unit
```

`print_tbreak nspaces offset` emits a 'full' tabulation break hint.

If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces.

If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box.

If the pretty-printer splits the line, `offset` is added to the current indentation.

## Ellipsis

```rust
val pp_set_ellipsis_text: formatter -> string -> unit
```

```rust
val set_ellipsis_text: string -> unit
```

Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, ., by default).

```rust
val pp_get_ellipsis_text: formatter -> unit -> string
```

```rust
val get_ellipsis_text: unit -> string
```

Return the text of the ellipsis.

## Semantic tags

```rust
type stag = ..
```

Semantic tags (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities.

Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so:

```rust
type stag += RGB of {r:int;g:int;b:int}
```

In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using `Format.pp_open_stag[29.23]` and `Format.pp_close_stag[29.23]`.

Tag specific operations occur any time a tag is opened or closed. At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*:

* The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation.
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.

# 28.31 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`[28.52] 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**
* The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations.

Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the
rendering device, while tag-printing allows fine tuning of printing routines to print the same
entity differently according to the semantic tags (i.e. print additional material or even omit
parts of the output).

More precisely: when a semantic tag is opened or closed then both and successive
'tag-printing' and 'tag-marking' operations occur:

* Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation).

* Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. 'tag-closing marker') for direct output into the output device of the formatter.

Being written directly into the output device of the formatter, semantic tag marker strings
are not considered as part of the printing material that drives line splitting (in other words,
the length of the strings corresponding to tag markers is considered as zero for line splitting).

Thus, semantic tag handling is in some sense transparent to pretty-printing and does not
interfere with usual indentation. Hence, a single pretty-printing routine can output both
simple 'verbatim' material or richer decorated output depending on the treatment of tags. By
default, tags are not active, hence the output is not decorated with tag information. Once
`set tags` is set to true, the pretty-printer engine honors tags and decorates the output
accordingly.

Default tag-marking functions behave the HTML way: `string tags[29.23]` are enclosed in "<"
and ">" while other tags are ignored; hence, opening marker for tag string "t" is "<t>" and
closing marker is "</t>".

Default tag-printing functions just do nothing.

Tag-marking and tag-printing functions are user definable and can be set by calling
`Format.set_formatter_stag_functions[29.23]`.

Semantic tag operations may be set on or off with `Format.set tags[29.23]`. Tag-marking
operations may be set on or off with `Format.set_mark tags[29.23]`. Tag-printing operations
may be set on or off with `Format.set_print tags[29.23]`.

Since: 4.08

type tag = string
type stag +=
| String_tag of tag
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` 1 is true if and only if 1 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 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

List reversal.

val init : int -> (int -> 'a) -> 'a list
`String_tag s` is a string tag of type `s`. String tags can be inserted either by explicitly using the constructor `String_tag` or by using the dedicated format syntax `"@{
 ... @}"`.

**Since: 4.08**

```hkl
val pp_open_stag : formatter -> stag -> unit
```

```hkl
val open_stag : stag -> unit
```

`pp_open_stag` ppf t opens the semantic tag named t.

The `print_open_stag` tag-printing function of the formatter is called with t as argument; then the opening tag marker for t, as given by `mark_open_stag t`, is written into the output device of the formatter.

**Since: 4.08**

```hkl
val pp_close_stag : formatter -> unit -> unit
```

```hkl
val close_stag : unit -> unit
```

`pp_close_stag` ppf () closes the most recently opened semantic tag t.

The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with t as argument.

**Since: 4.08**

```hkl
val pp_seteloags : formatter -> bool -> unit
```

```hkl
val seteloags : bool -> unit
```

`pp_seteloags` ppf b turns on or off the treatment of semantic tags (default is off).

```hkl
val pp_set_printeloags : formatter -> bool -> unit
```

```hkl
val set_printeloags : bool -> unit
```

`pp_set_printeloags` ppf b turns on or off the tag-printing operations.

```hkl
val pp_set_markeloags : formatter -> bool -> unit
```

```hkl
val set_markeloags : bool -> unit
```

`pp_set_markeloags` ppf b turns on or off the tag-marking operations.

```hkl
val pp_get_printeloags : formatter -> unit -> bool
```

```hkl
val get_printeloags : unit -> bool
```

Return the current status of tag-printing operations.

```hkl
val pp_get_markeloags : formatter -> unit -> bool
```

```hkl
val get_markeloags : unit -> bool
```

Return the current status of tag-marking operations.

```hkl
val pp_set_formateroChannel : formatter -> out_channel -> unit
```
init len f is [f 0; f 1; ...; f (len-1)], evaluated left to right.

**Since:** 4.06

**Raises:** Invalid_argument if len < 0.

val append : 'a list -> 'a list -> 'a list

append 10 11 appends 11 to 10. Same function as the infix operator `@`.

**Since:** 5.1 this function is tail-recursive.

val rev_append : 'a list -> 'a list -> 'a list

rev_append 11 12 reverses 11 and concatenates it with 12. This is equivalent to `(List.rev[28.31] 11) @ 12`.

val concat : 'a list list -> 'a list

Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).

val flatten : 'a list list -> 'a list

Same as `List.concat[28.31]`. Not tail-recursive (length of the argument + length of the longest sub-list).

## Comparison

val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool

equal eq [a1; ...; an] [b1; ...; bm] holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`.

**Note:** the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check `List compare_length s[28.31]` first.

**Since:** 4.12

val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int

compare cmp [a1; ...; an] [b1; ...; bm] performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as `compare[27.2]`:

* `a1 :: 11` is smaller than `a2 :: 12` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `11` is smaller than `12`

* the empty list `[]` is strictly smaller than non-empty lists

**Note:** the `cmp` function will be called even if the lists have different lengths.

**Since:** 4.12
## Redirecting the standard formatter output

val set_formatter_out_channel : out_channel -> unit

Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.)

set_formatter_out_channel is equivalent to
Format.pp_set_formatter_out_channel[29.23] std_formatter.

val pp_set_formatter_output_functions :  
formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit

val set_formatter_output_functions :  
(string -> int -> int -> unit) -> (unit -> unit) -> unit

pp_set_formatter_output_functions ppf out flush redirects the standard  
pretty-printer output functions to the functions out and flush.

The out function performs all the pretty-printer string output. It is called with a string s, a start position p, and a number of characters n; it is supposed to output characters p to p + n - 1 of s.

The flush function is called whenever the pretty-printer is flushed (via conversion %!, or pretty-printing indications @? or @., or using low level functions print_flush or print_newline).

val pp_get_formatter_output_functions :  
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)

val get_formatter_output_functions :  
unit -> (string -> int -> int -> unit) * (unit -> unit)

Return the current output functions of the standard pretty-printer.

## Redefining formatter output

The Format module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed!

## Redefining output functions

type formatter_out_functions =
{
  out_string : string -> int -> int -> unit ;
  out_width : string -> pos:int -> len:int -> int ;

  Since: 5.4
  out_flush : unit -> unit ;
  out_newline : unit -> unit ;
  out-spaces : int -> unit ;
  out-indent : int -> unit ;
Iterators

val iter : ('a -> unit) -> 'a list -> unit

iter f [a1; ...; an] applies function f in turn to [a1; ...; an]. It is equivalent to f
a1; f a2; ...; f an.

val iteri : (int -> 'a -> unit) -> 'a list -> unit

Same as List.iter[28.31], but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.

Since: 4.00

val map : ('a -> 'b) -> 'a list -> 'b list
map f [a1; ...; an] applies function f to a1, ..., an, and builds the list [f a1; ...;
f an] with the results returned by f.

val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list
Same as List.map[28.31], but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.

Since: 4.00

val rev_map : ('a -> 'b) -> 'a list -> 'b list
rev_map f l gives the same result as List.rev[28.31] (List.map[28.31] f l), but is more
efficient.

val filter_map : ('a -> 'b option) -> 'a list -> 'b list
filter_map f l applies f to every element of l, filters out the None elements and returns
the list of the arguments of the Some elements.

Since: 4.08

val concat_map : ('a -> 'b list) -> 'a list -> 'b list
concat_map f l gives the same result as List.concat[28.31] (List.map[28.31] f l).
Tail-recursive.

Since: 4.10

val fold_left_map :
('acc -> 'a -> 'acc * 'b) -> 'acc -> 'a list -> 'acc * 'b list

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 : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc
fold_left f init [b1; ...; bn] is f (... (f (init b1) b2) ...) bn.

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

}

The set of output functions specific to a formatter:

* the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`.

* the `out_width` function informs the formatting engine of the width of the substring as rendered on the output device. Explicit width information as provided by `@<n>`, `Format.pp_print_as[29.23]` or `Format.pp_print_substring_as[29.23]` takes priority over this function. Moreover, the formatting engine evaluates the width of the string arguments of `Format.pp_print_string[29.23]` and substring arguments of `Format.pp_print_substring[29.23]` as a whole. Consequently, `out_width` can be used to compute an approximative width for unicode substrings.

* the `out_flush` function flushes the pretty-printer output device.

* `out_newline` is called to open a new line when the pretty-printer splits the line.

* the `out-spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output.

* the `out indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line.

By default:

* fields `out_string` and `out_flush` are output device specific; (e.g. `output_string[28.2]` and `flush[28.2]` for a `out_channel[28.2]` device, or `Buffer.add_substring` and `ignore[28.2]` for a `Buffer.t` output device),

* field `out_width` is the number of unicode scalar values (see `Format.utf_8_scalar_width[29.23]`) in the substring.

* field `out_newline` is equivalent to `out_string "\n" 0 1;`

* fields `out-spaces` and `out indent` are equivalent to `out_string (String.make n ' ) 0 n.`

Since: 4.01

```perl
val pp_set_formatter_out_functions :
    formatter -> formatter_out_functions -> unit

val set_formatter_out_functions : formatter_out_functions -> unit
    pp_set_formatter_out_functions ppf out_funs Set all the pretty-printer output
    functions of ppf to those of argument out_funs,
```

This way, you can change the meaning of indentation (which can be something else than just
printing space characters) and the meaning of new lines opening (which can be connected to
any other action needed by the application at hand).
## Iterators on two lists

val iter2: ('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: ('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: ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
rev_map2 f 11 12 gives the same result as List.rev[28.31] (List.map2[28.31] f 11 12),
but is more efficient.

val fold_left2:
('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a list -> 'b list -> 'acc
fold_left2 f init [a1; ...; an] [b1; ...; bn] is f (... (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:
('a -> 'b -> 'acc -> 'acc) -> 'a list -> 'b list -> '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.

## List scanning

val for_all: ('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: ('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: ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
Same as List.for_all[28.31], but for a two-argument predicate.
**Raises** Invalid_argument if the two lists are determined to have different lengths.
Reasonable defaults for functions `out spaces`, `out newline`, and `out width` are respectively `out funs.out string` (String.make n ' ') 0 n, `out funs.out string "\n"` 0 1 and `Format.utf_8 scalar width` [29.23].

**Since: 4.01**

```hkl
val pp_get_formatter_out_functions :
    formatter -> unit -> formatter_out_functions
```

```hkl
val get_formatter_out_functions : unit -> formatter_out_functions
```

Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards.

**Since: 4.01**

```hkl
val utf_8_scalar_width : string -> pos:int -> len:int -> int
```

`utf_8_scalar_width` s ~`pos` ~`len` is the number of unicode scalar values in the substring `String.sub s pos len`. Invalid byte sequences are implicitly replaced by `U+FFFD` since this yields a better width approximation for other ascii-based encoding scheme like ISO-8859-15. This is the default `out_width` function since OCaml 5.4.

**Since: 5.4**

```hkl
val ascii_width : string -> pos:int -> len:int -> int
    ascii_width s ~pos ~len is len.
```

**Since: 5.4**

## Redefining semantic tag operations

```hkl
type formatter_stag_functions =
{ mark_open_stag : stag -> string ;
  mark_close_stag : stag -> string ;
  print_open_stag : stag -> unit ;
  print_close_stag : stag -> unit ;
}
```

The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened.

**Since: 4.08**

```hkl
val pp_set_formatter_stag_functions :
    formatter -> formatter_stag_functions -> unit
```

```hkl
val set_formatter_stag_functions : formatter_stag_functions -> unit
```
`val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool`

Same as `List.exists[28.31]`, but for a two-argument predicate.

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

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

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

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

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

## List searching

`val find : ('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 : ('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 : ('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

`val find_map : ('a -> 'b option) -> 'a list -> 'b option`

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

**Since:** 4.10

`val find_mapi : (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

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

`filter` f 1 returns all the elements of the list 1 that satisfy the predicate f. The order of the elements in the input list is preserved.
`pp_set_formatter_stag_functions` `ppf` `tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`.

When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name.

The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue.

**Since: 4.08**

```hkl
val pp_get_formatter_stag_functions :
    formatter -> unit -> formatter_stag_functions
```

```hkl
val get_formatter_stag_functions : unit -> formatter_stag_functions
```

Return the current semantic tag operation functions of the standard pretty-printer.

**Since: 4.08**

## Defining formatters

Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently.

For instance, given a `Buffer.t[29.7]` buffer `b`, `Format formatter_of_buffer[29.23] b` returns a new formatter using buffer `b` as its output device. Similarly, given a `out_channel[28.2]` output channel `oc`, `Format formatter_of_out_channel[29.23] oc` returns a new formatter using channel `oc` as its output device.

Alternatively, given `out_funs`, a complete set of output functions for a formatter, then `Format formatter_of_out_functions[29.23] out_funs` computes a new formatter using those functions for output.

```hkl
val formatter_of_out_channel : out_channel -> formatter
```

`formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`.

```hkl
val synchronized_formatter_of_out_channel :
    out_channel -> formatter Domain.DLS.key
```

`synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`.

When the formatter is 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]`.

**Alert unstable**
`val find_all : ('a -> bool) -> 'a list -> 'a list`

`find_all` is another name for `List.filter`[28.31].

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

Same as `List.filter`[28.31], 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

`val partition : ('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 `1` that satisfy the predicate `f`, and `12` is the list of all the elements of `1` that do not satisfy `f`. The order of the elements in the input list is preserved.

`val partition_map : ('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 `1`:

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

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

The output elements are included in `11` and `12` in the same relative order as the corresponding input elements in `1`.

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

**Since:** 4.12

## 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 `List.assoc`[28.31], but uses physical equality instead of structural equality to compare keys.
val std_formatter : formatter

The initial domain's standard formatter to write to standard output.

It is defined as `Format formatter_of_out_channel[29.23] stdout[28.2]`.

val get_std_formatter : unit -> formatter

`get_std_formatter ()` returns the current domain's standard formatter used to write to standard output.

**Since: 5.0**

val err_formatter : formatter

The initial domain's formatter to write to standard error.

It is defined as `Format formatter_of_out_channel[29.23] stderr[28.2]`.

val get_err_formatter : unit -> formatter

`get_err_formatter ()` returns the current domain's formatter used to write to standard error.

**Since: 5.0**

val formatter_of_buffer : Buffer.t -> formatter

`formatter_of_buffer` b returns a new formatter writing to buffer b. At the end of pretty-printing, the formatter must be flushed using `Format.pp_print_flush[29.23]` or `Format.pp_print_newline[29.23]`, to print all the pending material into the buffer.

val stdbuf : Buffer.t

The initial domain's string buffer in which `str_formatter` writes.

val get_stdbuf : unit -> Buffer.t

`get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes.

**Since: 5.0**

val str_formatter : formatter

The initial domain's formatter to output to the `Format.stdbuf[29.23]` string buffer.

`str_formatter` is defined as `Format formatter_of_buffer[29.23] Format.stdbuf[29.23]`.

val get_str_formatter : unit -> formatter

The current domain's formatter to output to the current domain's string buffer.

**Since: 5.0**

val flush_str_formatter : unit -> string

Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer.
val assq_opt : 'a -> ('a * 'b) list -> 'b option

Same as `List.assoc_opt[28.31]`, but uses physical equality instead of structural equality to compare keys.

Since: 4.05

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

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

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

Same as `List.mem[28.31]`, but uses physical equality instead of structural equality to compare keys.

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

`remove\_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive.

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

Same as `List.remove\_assoc[28.31]`, 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.

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

val sort : ('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. `List.sort[28.31]` 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.
val make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter

make_formatter out flush returns a new formatter that outputs with function out, and
flushes with function flush.

For instance,

make_formatter
(Stdlib.output_substring oc)
 fun () -> Stdlib.flush oc

returns a formatter to the out_channel [28.2] oc.

val make_synchronized_formatter :
(string -> int -> int -> unit) ->
(unit -> unit) -> formatter Domain.DLS.key

make_synchronized_formatter out flush returns the key to the domain-local state that
holds the domain-local formatter that outputs with function out, and flushes with function
flush.

When the formatter is 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].

Since: 5.0

Alert unstable

val formatter_of_out_functions : formatter_out_functions -> formatter
formatter_of_out_functions out_funs returns a new formatter that writes with the set
of output functions out_funs.

See definition of type Format formatter_out_functions [29.23] for the meaning of
argument out_funs.

Since: 4.06

## Symbolic pretty-printing

Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs
symbolic pretty-printing items.

When using a symbolic formatter, all regular pretty-printing activities occur but output material
is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output
buffer allows post-processing of symbolic output before performing low level output operations.

In practice, first define a symbolic output buffer b using:

* `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with:

* `let ppf = formatter_of_symbolic_output_buffer sob`
val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list

Same as List.sort[28.31], 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.

val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list

Same as List.sort[28.31] or List.stable_sort[28.31], whichever is faster on typical input.

val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list

Same as List.sort[28.31], but also remove duplicates.

Since: 4.02 (4.03 in ListLabels)

val merge : ('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

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

Iterate on the list.

Since: 4.07

val of_seq : 'a Seq.t -> 'a list

Create a list from a sequence.

Since: 4.07

28.32 Module ListLabels : 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[28.52] module.

type 'a t = 'a list =
| []
| (::) of 'a * 'a list
Use symbolic formatter ppf as usual, and retrieve symbolic items at end of pretty-printing by
flushing symbolic output buffer sob with:

* `flush_symbolic_output_buffer` sob.

`type symbolic_output_item =`

| `Output_flush`
symbolic flush command

| `Output_newline`
symbolic newline command

| `Output_string` of `string`
`Output_string` s: symbolic output for string s

| `Output-spaces` of `int`
`Output-spaces` n: symbolic command to output n spaces

| `Output indent` of `int`
`Output indent` i: symbolic indentation of size i

Items produced by symbolic pretty-printers

Since: 4.06

`type symbolic_output_buffer`

The output buffer of a symbolic pretty-printer.

Since: 4.06

`val make_symbolic_output_buffer : unit -> symbolic_output_buffer`
`make_symbolic_output_buffer` () returns a fresh buffer for symbolic output.

Since: 4.06

`val clear_symbolic_output_buffer : symbolic_output_buffer -> unit`
`clear_symbolic_output_buffer` sob resets buffer sob.

Since: 4.06

`val get_symbolic_output_buffer :`

symbolic_output_buffer -> symbolic_output_item list
`get_symbolic_output_buffer` sob returns the contents of buffer sob.

Since: 4.06

`val flush_symbolic_output_buffer :`

symbolic_output_buffer -> symbolic_output_item list
`flush_symbolic_output_buffer` sob returns the contents of buffer sob and resets buffer
sob. `flush_symbolic_output_buffer` sob is equivalent to `let items =`
`get_symbolic_output_buffer` sob in `clear_symbolic_output_buffer` sob; items

Since: 4.06
An alias for the type of lists.

`val length : 'a list -> int`

Return the length (number of elements) of the given list.

`val compare_lengths : 'a list -> 'b list -> int`

Compare the lengths of two lists. `compare_lengths 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

`val compare_length_with : 'a list -> len: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` 1 is true if and only if 1 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.05

`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`
```rust
val add_symbolic_output_item :
```

```
symbolic_output_buffer -> symbolic_output_item -> unit
add_symbolic_output_item sob itm adds item itm to buffer sob.
```

**Since: 4.06**

```rust
val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter
```

```
formatter_of_symbolic_output_buffer sob returns a symbolic formatter that outputs to
symbolic_output_buffer sob.
```

**Since: 4.06**

## Convenience formatting functions.

```rust
val pp_print_iter :
```

```
?pp_sep: (formatter -> unit -> unit) ->
(( 'a -> unit) -> 'b -> unit) ->
( formatter -> 'a -> unit) -> formatter -> 'b -> unit
pp_print_iter ~pp_sep iter pp_v ppf v formats on ppf the iterations of iter over a
collection v of values using pp_v. Iterations are separated by pp_sep (defaults to
Format.pp_print_cut[29.23]).
```

**Since: 5.1**

```rust
val pp_print_list :
```

```
?pp_sep: (formatter -> unit -> unit) ->
( formatter -> 'a -> unit) -> formatter -> 'a list -> unit
pp_print_list ?pp_sep pp_v ppf l prints items of list l, using pp_v to print each item,
and calling pp_sep between items (pp_sep defaults to Format.pp_print_cut[29.23]). Does
nothing on empty lists.
```

**Since: 4.02**

```rust
val pp_print_array :
```

```
?pp_sep: (formatter -> unit -> unit) ->
( formatter -> 'a -> unit) -> formatter -> 'a array -> unit
pp_print_array ?pp_sep pp_v ppf a prints items of array a, using pp_v to print each
item, and calling pp_sep between items (pp_sep defaults to Format.pp_print_cut[29.23]).
Does nothing on empty arrays.
```

If a is mutated after `pp_print_array` is called, the printed values may not be what is
expected because `Format` can delay the printing. This can be avoided by flushing `ppf`.

**Since: 5.1**

```rust
val pp_print_seq :
```

```
?pp_sep: (formatter -> unit -> unit) ->
( formatter -> 'a -> unit) ->
formatter -> 'a Seq.t -> unit
```
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
List reversal.

val init : len:int -> f:(int -> 'a) -> 'a list
init ~len ~f is [f 0; f 1; ...; f (len-1)], evaluated left to right.

**Since:** 4.06

**Raises:** `Invalid_argument` if `len` < 0.

val append : 'a list -> 'a list -> 'a list
`append` 10 11 appends 11 to 10. Same function as the `infix` operator `@`.

**Since:** 5.1 this function is tail-recursive.

val rev_append : 'a list -> 'a list -> 'a list
`rev_append` 11 12 reverses 11 and concatenates it with 12. This is equivalent to
(`ListLabels.rev`[28.32] 11) @ 12.

val concat : 'a list list -> 'a list
Concatenate a list of lists. The elements of the argument are all concatenated together (in the
same order) to give the result. Not tail-recursive (length of the argument + length of the
longest sub-list).

val flatten : 'a list list -> 'a list
Same as `ListLabels.concat`[28.32]. Not tail-recursive (length of the argument + length of
the longest sub-list).

## Comparison

val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool
equal eq [a1; ...; an] [b1; ...; bm] holds when the two input lists have the same
length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`.

Note: the `eq` function may be called even if the lists have different length. If you know your
equality function is costly, you may want to check `ListLabels compare_length s`[28.32] first.

**Since:** 4.12

val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int
`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the
two input lists, using the same `'a -> 'a -> int` interface as `compare`[27.2]:
`pp_print_seq` ?`pp_sep` `pp_v` `ppf` `s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to `Format.pp_print_cut[29.23]`). Does nothing on empty sequences.

This function does not terminate on infinite sequences.

**Since: 4.12**

val `pp_print_text`: `formatter` -> `string` -> `unit`

`pp_print_text` `ppf` `s` prints `s` with spaces and newlines respectively printed using `Format.pp_print_space[29.23]` and `Format.pp_force_newline[29.23]`.

**Since: 4.02**

val `format_text` :
('a, 'b, 'c, 'd, 'e, 'f) `format6` ->
('a, 'b, 'c, 'd, 'e, 'f) `format6`

`format_text` `fmt` replaces spaces and newlines in the format string literal `fmt` with hint breaks or forced newlines:

* Blank lines (lines made only of spaces (`U+0020`)) are replaced by "`@n`".

* Sequences of spaces and a newline (`U+000A`) preceding a blank line are replaced by "`@n`": blank lines remain blank lines in the output.

* Remaining sequences made of `k` spaces and newlines are replaced by "`@;<0 k'>`" where `k' = max 1 k` is at least 1.

* Breaks can be avoided using non-breaking space characters (`U+00A0`).

* Lines can be forced by using "`@\n`"

**Since: 5.4**

val `pp_print_option` :
?`none`: (`formatter` -> `unit` -> `unit`) ->
`formatter` -> 'a' -> `unit` -> `formatter` -> 'a' `option` -> `unit`

`pp_print_option` ?`none` `pp_v` `ppf` `o` prints `o` on `ppf` using `pp_v` if `o` is Some `v` and `none` if it is None. `none` prints nothing by default.

**Since: 4.08**

val `pp_print_result` :
`ok`: (`formatter` -> 'a' -> `unit`) ->
`error`: (`formatter` -> 'e' -> `unit`) ->
`formatter` -> ('a', 'e') `result` -> `unit`

`pp_print_result` ~`ok` ~`error` `ppf` `r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`.

**Since: 4.08**
* `a1 :: 11` is smaller than `a2 :: 12` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `11` is smaller than `12`

* the empty list `[]` is strictly smaller than non-empty lists

Note: the `cmp` function will be called even if the lists have different lengths.

**Since:** 4.12

## Iterators

`val iter : f:('a -> unit) -> 'a list -> unit`

`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`.

`val iteri : f:(int -> 'a -> unit) -> 'a list -> unit`

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

**Since:** 4.00

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

`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`.

`val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list`

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

**Since:** 4.00

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

`rev_map ~f l` gives the same result as `ListLabels.rev` [28.32] (`ListLabels.map` [28.32] `f l`), but is more efficient.

`val filter_map : f:('a -> 'b option) -> 'a list -> 'b list`

`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements.

**Since:** 4.08

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

`concat_map ~f l` gives the same result as `ListLabels.concat` [28.32] (`ListLabels.map` [28.32] `f l`). Tail-recursive.

**Since:** 4.10

`val fold_left_map :`

`f:('acc -> 'a -> 'acc * 'b) -> init:'acc -> 'a list -> 'acc * 'b list`
```python
val pp_print_either :
    left: (formatter -> 'a -> unit) ->
    right: (formatter -> 'b -> unit) ->
formatter -> ('a, 'b) Either.t -> unit

pp_print_either ~left ~right ppf e prints e on ppf using left if e is EitherLeft
_ and right if e is Either RIGHT _
```

Since: 4.13

## Formatted pretty-printing

Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications.

Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine.

Those annotations are introduced in the format strings using the `@` character. For instance, `@` means a space break, `@`, means a cut, `@[` opens a new box, and `@]` closes the last open box.

```python
val fprintf : formatter -> ('a, formatter, unit) format -> 'a
fprintf ff fmt arg1 ... argN formats the arguments arg1 to argN according to the format string fmt, and outputs the resulting string on the formatter ff.
```

The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the `Format` module, and pretty-printing indications specific to the `Format` module.

The pretty-printing indication characters are introduced by a `@` character, and their meanings are:

* `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. 'h' stands for an 'horizontal' pretty-printing box, 'v' stands for a 'vertical' pretty-printing box, 'hv' stands for an 'horizontal/vertical' pretty-printing box, 'b' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, 'hov' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[<hov 2>` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`.

* `@]`: close the most recently opened pretty-printing box.

* `@,`: output a 'cut' break hint, as with `print_cut()`.

* `@ :` output a 'space' break hint, as with `print_space()`.

* `@;`: output a 'full' break hint as with `print_break`. The `nspaces` and `offset` parameters of the break hint may be optionally specified with the following syntax: the `<` character, followed by an integer `nspaces` value, then an integer `offset`, and a closing `>` character. If no parameters are provided, the full break defaults to a 'space' break hint.