behave mostly as one would expect: non-atomic reads and writes in C will race with non-atomic reads and writes in OCaml, and C atomics will not race with OCaml atomics. There is one theoretical possibility of false positive: if a *value* is initialized from C without using `caml_initialize` (which is allowed under the condition that the GC does not run between the allocation and the write, see Chapter 22) and a conflicting access is made later by another thread. This does not constitute a data race, but TSan may report it as such.

## 27.4 Runtime options

TSan supports a number of configuration options at runtime using the `TSAN_OPTIONS` environment variable. `TSAN_OPTIONS` should contain one or more options separated by spaces. See the documentation of TSan flags and the documentation of flags common to all sanitizers for more information. Notably, `TSAN_OPTIONS` allows suppressing some data races from TSan reports. Suppressing data race reports is useful for intentional races or libraries that cannot be fixed.

For example, to suppress reports originating from functions in the OCaml module `My_module`, one can run

`TSAN_OPTIONS="suppressions=suppr.txt" ./my_instrumented_program`

with `suppr.txt` a file containing:

`race_top: ^camlMy_module`

(Note that this depends on the format of OCaml symbols in the executable. Some builders, like Dune, might result in different formats. You should adapt this example to the symbols effectively present in your stack traces.)

The `TSAN_OPTIONS` variable also allows for increasing the “history size”, e.g.:

`TSAN_OPTIONS="history_size=7" ./my_instrumented_program`

TSan's history records events such as function entry and exit, and is used to reconstruct stack traces. Increasing the history size can sometimes be necessary to obtain the second stack trace, but it also increases memory consumption. This setting does not change the number of memory accesses remembered per memory location.

Another useful runtime option is `exitcode=0`, which still reports data races but does not change the exit code. This can be useful if TSan complains about data races in programs that you don't care about and the non-zero exit code disturbs your workflow.

## 27.5 Guidelines for linking

As a general rule, OCaml programs instrumented with TSan should only be linked with OCaml or C objects also instrumented with TSan. Doing otherwise may result in crashes. The only exception to this rule are C libraries that do not call into the OCaml runtime system in any way, i.e., do not allocate, raise exceptions, call back into OCaml code, etc. Examples include the libc or system libraries. Data races in non-instrumented libraries will not be reported.
## Operations on format strings

Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module `Scanf[27.2]` and to print data with formatted output functions from modules `Printf[27.2]` and `Format[27.2]`.

Format strings are made of three kinds of entities:

* *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print,

* *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument,

* *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output.

There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`.

For more information about conversion specifications and formatting indications available, read the documentation of modules `Scanf[27.2]`, `Formatf[27.2]` and `Format[27.2]`.

Format strings have a general and highly polymorphic type (`'a', 'b', 'c', 'd', 'e', 'f' format6. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml.

The meaning of format string type parameters is as follows:

* `'a` is the type of the parameters of the format for formatted output functions (*printf*-style functions); `'a` is the type of the values read by the format for formatted input functions (*scanf*-style functions).

* `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For *printf*-style functions from module `Formatf[27.2]`, `'b` is typically `out_channel`; for *printf*-style functions from module `Format[27.2]`, `'b` is typically `Format formatter[28.21]`; for *scanf*-style functions from module `Scanf[27.2]`, `'b` is typically `Scanf Scanning in_channel[28.47]`.

Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion.

* `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf*-style functions or to the kscanf*-style functions.

* `'d` is the type of parameters for the `scanf*-style functions.

* `'e` is the type of the receiver function for the `scanf*-style functions.
C code interacting with OCaml should always be built through the `ocamlopt` command, which will pass the required instrumentation flags to the C compiler. The `CAMLno_tsan` qualifier can be used to prevent functions from being instrumented:

```c
CAMLno_tsan void f(int arg)
{
    /* This function will not be instrumented. */
    ...
}
```

Races from non-instrumented functions will not be reported. `CAMLno_tsan` should only be used by experts. It can be used to reduce the performance overhead in certain corner cases, or to suppress some known alarms. For the latter, using a suppressions file with `TSAN_OPTIONS` should be preferred when possible, as it allows for finer-grained control, and qualifying a function `f` with `CAMLno_tsan` results in missing entries in TSan's stack traces when a data race happens in a transitive callee of `f`.

There is no way to disable instrumentation in OCaml code.

## 27.6 Changes in the delivery of signals

TSan intercepts all signals and passes them down to the instrumented program. This overlay from TSan is not always transparent for the program. Synchronous signals such as `SIGSEV`, `SIGILL`, `SIGBUS`, etc. will be passed down immediately, whereas asynchronous signals such as `SIGINT` will be delayed until the next call to the TSan runtime (e.g. until the next access to mutable data). This limitation of TSan can have surprising effects: for instance, pure, recursive functions that do not allocate cannot be interrupted until they terminate.
* 'f is the final result type of a formatted input/output function invocation: for the `printf`-style functions, it is typically `unit`; for the `scanf`-style functions, it is typically the result type of the receiver function.

`type ('a, 'b, 'c, 'd, 'e, 'f) format6 = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6`

`type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6`

`type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4`

`val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string`

Converts a format string into a string.

`val format_of_string :`

```
('a, 'b, 'c, 'd, 'e, 'f) format6 ->
```

```
('a, 'b, 'c, 'd, 'e, 'f) format6
```

`format_of_string` s returns a format string read from the string literal s. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general `Scanf.format_from_string[28.47]` function.

`val (~~) :`

```
('a, 'b, 'c, 'd, 'e, 'f) format6 ->
```

```
('f, 'b, 'c, 'e, 'g, 'h) format6 ->
```

```
('a, 'b, 'c, 'd, 'g, 'h) format6
```

`f1 ~~ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see `Ocaml_operators[28.60]` for more information.

## Program termination

`val exit : int -> 'a`

Terminate the process, returning the given status code to the operating system: usually `0` to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with `Domain.at_exit[28.14]` are called followed by those registered with `at_exit[27.2]`.

An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception.

`val at_exit : (unit -> unit) -> unit`

Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following:

* executes `exit[27.2]`

* terminates, either normally or because of an uncaught exception
* executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first.

## Standard library modules

* `module Arg :`

* `Arg`

* `module Array :`

* `Array`

* `module ArrayLabels :`

* `ArrayLabels`

* `module Atomic :`

* `Atomic`

* `module Bigarray :`

* `Bigarray`

* `module Bool :`

* `Bool`

* `module Buffer :`

* `Buffer`

* `module Bytes :`

* `Bytes`

* `module BytesLabels :`

* `BytesLabels`

* `module Callback :`

* `Callback`

* `module Char :`

* `Char`

* `module Complex :`

* `Complex`

* `module Condition :`

* `Condition`

* `module Digest :`

* `Digest`

* `module Domain :`

* `Domain`

**Alert unstable.** The Domain interface may change in incompatible ways in the future.

* `module Effect :`

* `Effect`

**Alert unstable.** The Effect interface may change in incompatible ways in the future.
# Part IV

## The OCaml library
module Either :

Either

module Ephemeron :

Ephemeron

module Filename :

Filename

module Float :

Float

module Format :

Format

module Fun :

Fun

module Gc :

Gc

module Hashtbl :

Hashtbl

module In_channel :

In_channel

module Int :

Int

module Int32 :

Int32

module Int64 :

Int64

module Lazy :

Lazy

module Lexing :

Lexing

module List :

List

module ListLabels :

ListLabels

module Map :

Map

module Marshal :

Marshal

module MoreLabels :

MoreLabels

module Mutex :

Mutex

module Nativeint :
<figure><img src="image_6.png" /></figure>
Nativeint
module Obj :
    Obj
module Oo :
    Oo
module Option :
    Option
module Out_channel :
    Out_channel
module Parsing :
    Parsing
module Printexc :
    Printexc
moduleuntf :
   untf
module Queue :
    Queue
module Random :
    Random
module Result :
    Result
module Scanf :
    Scanf
module Semaphore :
    Semaphore
module Seq :
    Seq
module Set :
    Set
module Stack :
    Stack
module StdLabels :
    StdLabels
module String :
    String
module StringLabels :
    StringLabels
module Sys :
    Sys
module Type :
    Type
# Chapter 28

## The core library

This chapter describes the OCaml core library, which is composed of declarations for built-in types and exceptions, plus the module `Stdlib` that provides basic operations on these built-in types. The `Stdlib` module is special in two ways:

* It is automatically linked with the user's object code files by the `ocamlc` command (chapter 13).

* It is automatically "opened" when a compilation starts, or when the toplevel system is launched. Hence, it is possible to use unqualified identifiers to refer to the functions provided by the `Stdlib` module, without adding a `open Stdlib` directive.

### Conventions

The declarations of the built-in types and the components of module `Stdlib` are printed one by one in typewriter font, followed by a short comment. All library modules and the components they provide are indexed at the end of this report.

### 28.1 Built-in types and predefined exceptions

The following built-in types and predefined exceptions are always defined in the compilation environment, but are not part of any module. As a consequence, they can only be referred by their short names.

#### Built-in types

**type int**

The type of integer numbers.

**type char**

The type of characters.

**type bytes**

The type of (writable) byte sequences.
module Uchar :

Uchar

module Unit :

Unit

module Weak :

Weak
type string

The type of (read-only) character strings.

type float

The type of floating-point numbers.

type bool = false | true

The type of booleans (truth values).

type unit = ()

The type of the unit value.

type exn

The type of exception values.

type 'a array

The type of arrays whose elements have type 'a.

type 'a list = [] | :: of 'a * 'a list

The type of lists whose elements have type 'a.

type 'a option = None | Some of 'a

The type of optional values of type 'a.

type int32

The type of signed 32-bit integers. Literals for 32-bit integers are suffixed by l. See the `Int32[29.29]` module.

type int64

The type of signed 64-bit integers. Literals for 64-bit integers are suffixed by L. See the `Int64[29.30]` module.

type nativeint

The type of signed, platform-native integers (32 bits on 32-bit processors, 64 bits on 64-bit processors). Literals for native integers are suffixed by n. See the `Nativeint[29.39]` module.

type ('a, 'b, 'c, 'd, 'e, 'f) format6

The type of format strings. 'a is the type of the parameters of the format, 'f is the result type for the `printf-style` functions, 'b is the type of the first argument given to `%a` and `%t` printing functions (see module `FORMAT[29.47]'), 'c is the result type of these functions, and also the type of the argument transmitted to the first argument of `kprintf-style` functions, 'd is the result type for the `scanf-style` functions (see module `SCANF[29.52]`), and 'e is the type of the receiver function for the `scanf-style` functions.

type 'a lazy_t

This type is used to implement the `Lazy[29.31]` module. It should not be used directly.
# Chapter 28

## The standard library

This chapter describes the functions provided by the OCaml standard library. The modules from the standard library are automatically linked with the user's object code files by the `ocamlc` command. Hence, these modules can be used in standalone programs without having to add any `.cmo` file on the command line for the linking phase. Similarly, in interactive use, these globals can be used in toplevel phrases without having to load any `.cmo` file in memory.

Unlike the core `Stdlib` module, submodules are not automatically “opened” when compilation starts, or when the toplevel system is launched. Hence it is necessary to use qualified identifiers to refer to the functions provided by these modules, or to add `open` directives.

### Conventions

For easy reference, the modules are listed below in alphabetical order of module names. For each module, the declarations from its signature are printed one by one in typewriter font, followed by a short comment. All modules and the identifiers they export are indexed at the end of this report.

### Overview

Here is a short listing, by theme, of the standard library modules.
## Predefined exceptions

**exception Match_failure of (string * int * int)**

Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).

**exception Assert_failure of (string * int * int)**

Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).

**exception Invalid_argument of string**

Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.

**exception Failure of string**

Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure _ instead).

**exception Not_found**

Exception raised by search functions when the desired object could not be found.

**exception Out_of_memory**

Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)

**exception Stack_overflow**

Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program. Before 4.10, it was not fully implemented by the native-code compiler.

**exception Sys_error of string**

Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys_error _ instead).

**exception End_of_file**

Exception raised by input functions to signal that the end of file has been reached.

**exception Division_by_zero**

Exception raised by integer division and remainder operations when their second argument is zero.
## Data structures:

<table><tr><td>String</td><td>p. 840</td><td>string operations</td></tr><tr><td>Bytes</td><td>p. 576</td><td>operations on byte sequences</td></tr><tr><td>Array</td><td>p. 530</td><td>array operations</td></tr><tr><td>List</td><td>p. 719</td><td>list operations</td></tr><tr><td>StdLabels</td><td>p. 840</td><td>labelized versions of the above 4 modules</td></tr><tr><td>Unit</td><td>p. 871</td><td>unit values</td></tr><tr><td>Bool</td><td>p. 569</td><td>boolean values</td></tr><tr><td>Char</td><td>p. 604</td><td>character operations</td></tr><tr><td>Uchar</td><td>p. 868</td><td>Unicode characters</td></tr><tr><td>Int</td><td>p. 702</td><td>integer values</td></tr><tr><td>Option</td><td>p. 780</td><td>option values</td></tr><tr><td>Result</td><td>p. 804</td><td>result values</td></tr><tr><td>Effect</td><td>p. 613</td><td>effect handlers</td></tr><tr><td>Either</td><td>p. 616</td><td>either values</td></tr><tr><td>Hashtbl</td><td>p. 686</td><td>hash tables and hash functions</td></tr><tr><td>Random</td><td>p. 801</td><td>pseudo-random number generator</td></tr><tr><td>Set</td><td>p. 829</td><td>sets over ordered types</td></tr><tr><td>Map</td><td>p. 736</td><td>association tables over ordered types</td></tr><tr><td>MoreLabels</td><td>p. 747</td><td>labelized versions of Hashtbl, Set, and Map</td></tr><tr><td>Oo</td><td>p. 779</td><td>useful functions on objects</td></tr><tr><td>Stack</td><td>p. 838</td><td>last-in first-out stacks</td></tr><tr><td>Queue</td><td>p. 797</td><td>first-in first-out queues</td></tr><tr><td>Buffer</td><td>p. 571</td><td>buffers that grow on demand</td></tr><tr><td>Seq</td><td>p. 816</td><td>functional iterators</td></tr><tr><td>Lazy</td><td>p. 714</td><td>delayed evaluation</td></tr><tr><td>Weak</td><td>p. 871</td><td>references that don't prevent objects from being garbage-collected</td></tr><tr><td>Atomic</td><td>p. 545</td><td>atomic references (for compatibility with concurrent runtimes)</td></tr><tr><td>Ephemeron</td><td>p. 617</td><td>ephemerons and weak hash tables</td></tr><tr><td>Bigarray</td><td>p. 547</td><td>large, multi-dimensional, numerical arrays</td></tr></table>

## Arithmetic:

<table><tr><td>Complex</td><td>p. 605</td><td>complex numbers</td></tr><tr><td>Float</td><td>p. 628</td><td>floating-point numbers</td></tr><tr><td>Int32</td><td>p. 705</td><td>operations on 32-bit integers</td></tr><tr><td>Int64</td><td>p. 709</td><td>operations on 64-bit integers</td></tr><tr><td>Nativeint</td><td>p. 775</td><td>operations on platform-native integers</td></tr></table>
**exception Sys_blocks_io**

A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel.

**exception Undefined_recurrent_module of (string * int * int)**

Exception raised when an ill-founded recursive module definition is evaluated. (See section 12.2.) The arguments are the location of the definition in the source code (file name, line number, column number).

## 28.2 Module Stdlib: The OCaml Standard library.

This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by Stdlib.

In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the standard library modules [28.2].

### Exceptions

**val raise : exn -> 'a**

Raise the given exception value

**val raise_notrace : exn -> 'a**

A faster version raise which does not record the backtrace.

**Since: 4.02**

**val invalid_arg : string -> 'a**

Raise exception Invalid_argument with the given string.

**val failwith : string -> 'a**

Raise exception Failure with the given string.

**exception Exit**

The Exit exception is not raised by any library function. It is provided for use in your programs.

**exception Match_failure of (string * int * int)**

Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number).

**exception Assert_failure of (string * int * int)**

Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number).
**input/output:**

<table><tr><td>In_channel</td><td>p. 698</td><td>input channels</td></tr><tr><td>Out_channel</td><td>p. 781</td><td>output channels</td></tr><tr><td>Format</td><td>p. 649</td><td>pretty printing with automatic indentation and line breaking</td></tr><tr><td> Marshal</td><td>p. 743</td><td>marshaling of data structures</td></tr><tr><td> Printf</td><td>p. 793</td><td>formatting printing functions</td></tr><tr><td>Scanf</td><td>p. 806</td><td>formatted input functions</td></tr><tr><td> Digest</td><td>p. 612</td><td>MD5 message digest</td></tr></table>

**Parsing:**

<table><tr><td>Lexing</td><td>p. 716</td><td>the run-time library for lexers generated by ocamllex</td></tr><tr><td>Parsing</td><td>p. 785</td><td>the run-time library for parsers generated by ocamlyacc</td></tr></table>

**System interface:**

<table><tr><td>Arg</td><td>p. 525</td><td>parsing of command line arguments</td></tr><tr><td>Callback</td><td>p. 603</td><td>registering OCaml functions to be called from C</td></tr><tr><td>Filename</td><td>p. 624</td><td>operations on file names</td></tr><tr><td>Gc</td><td>p. 677</td><td>memory management control and statistics</td></tr><tr><td>Printexc</td><td>p. 786</td><td>a catch-all exception handler</td></tr><tr><td>Sys</td><td>p. 858</td><td>system interface</td></tr></table>

**Multicore interface:**

<table><tr><td>Domain</td><td>p. 609</td><td>domain spawn and join</td></tr><tr><td>Mutex</td><td>p. 774</td><td>mutual exclusion locks</td></tr><tr><td>Condition</td><td>p. 607</td><td>condition variables</td></tr><tr><td>Semaphore</td><td>p. 836</td><td>semaphores</td></tr><tr><td>Effect</td><td>p. 613</td><td>deep and shallow effect handlers</td></tr></table>

**Misc:**

<table><tr><td>Fun</td><td>p. 676</td><td>function values</td></tr><tr><td>Type</td><td>p. 866</td><td>type introspection</td></tr></table>

**28.1 Module Arg : Parsing of command line arguments.**

This module provides a general mechanism for extracting options and arguments from the command line to the program. For example:

```
let usage_msg = "append [-verbose] <file1> [<file2>] ... -o <output>"
let verbose = ref false
let input_files = ref []
let output_file = ref ""
```
**exception Invalid_argument of string**

Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it.

**exception Failure of string**

Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use `Failure _` instead).

**exception Not_found**

Exception raised by search functions when the desired object could not be found.

**exception Out_of_memory**

Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.)

**exception Stack_overflow**

Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program.

Before 4.10, it was not fully implemented by the native-code compiler.

**exception Sys_error of string**

Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use `Sys_error _` instead).

**exception End_of_file**

Exception raised by input functions to signal that the end of file has been reached.

**exception Division_by_zero**

Exception raised by integer division and remainder operations when their second argument is zero.

**exception Sys_blocks_io**

A special case of `Sys_error` raised when no I/O is possible on a non-blocking I/O channel.

**exception Undefined_recursive_module of (string * int * int)**

Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number).
```python
let anon Fun filename =
    input_files := filename::!input_files

let speclist =
    [("-verbose", Arg.Set verbose, "Output debug information");
     ("-o", Arg.Set_string output_file, "Set output file name")]

let () =
    Arg.parse speclist anon Fun usage msg;
    (* Main functionality here *)
```

Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set_string`, `Int`, `Set_int`, `Float`, `Set_float`, `Tuple`, `Symbol`, `Rest`, `Rest_all` and `Expand`.

`Unit`, `Set` and `Clear` keywords take no argument.

A `Rest` or `Rest_all` keyword takes the remainder of the command line as arguments. (More explanations below.)

Every other keyword takes the following word on the command line as argument. For compatibility with GNU `getopt_long`, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments.

Examples (`cmd` is assumed to be the command name):

* `cmd -flag` (a unit option)

* `cmd -int 1` (an `int` option with argument `1`)

* `cmd -string foobar` (a string option with argument `foobar`)

* `cmd -float 12.34` (a `float` option with argument `12.34`)

* `cmd a b c` (three anonymous arguments: `"a"`, `"b"`, and `"c"`)

* `cmd a b -- c d` (two anonymous arguments and a `rest` option with two arguments)

`Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest_all` takes a function that is called once, with the list of all remaining arguments.

Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest_all` keyword is called with an empty list.

**Alert unsynchronized_access.** The `Arg` module relies on a mutable global state, parsing functions should only be called from a single domain.

```python
type spec =
| Unit of (unit -> unit)
    Call the function with unit argument
| Bool of (bool -> unit)
    Call the function with a `bool` argument
```
Comparisons

val (=) : 'a -> 'a -> bool

Alias of Repr equal [29.50] Left-associative operator, see Ocaml_operators [29.65] for more
information.

val (<>) : 'a -> 'a -> bool

Negation of Repr equal [29.50]. Left-associative operator, see Ocaml_operators [29.65] for
more information.

val (<) : 'a -> 'a -> bool

See (>=)[28.2]. Left-associative operator, see Ocaml_operators[29.65] for more information.

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

See (>=)[28.2]. Left-associative operator, see Ocaml_operators[29.65] for more information.

val (<=) : 'a -> 'a -> bool

See (>=)[28.2]. Left-associative operator, see Ocaml_operators[29.65] for more information.

val (>=) : 'a -> 'a -> bool

Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with Repr equal [29.50]. As in the case of Repr equal [29.50], mutable structures are compared by contents. Comparison between functional values raises Invalid_argument. Comparison between cyclic structures may not terminate. Left-associative operator, see Ocaml_operators [29.65] for more information.

val compare : 'a -> 'a -> int
Alias of Repr compare [29.50].

val min : 'a -> 'a -> 'a
Alias of Repr.min [29.50].

val max : 'a -> 'a -> 'a
Alias of Repr.max [29.50].

val (==) : 'a -> 'a -> bool

Alias of Repr.phys_equal [29.50]. Left-associative operator, see Ocaml_operators [29.65] for more information.

val (!=) : 'a -> 'a -> bool

Negation of Repr.phys_equal [29.50]. Left-associative operator, see Ocaml_operators [29.65]
for more information.
Boolean operations

val not : bool -> bool

The boolean negation.

val (&&) : bool -> bool -> bool

The boolean 'and'. Evaluation is sequential, left-to-right: in e1 && e2, e1 is evaluated first, and if it returns false, e2 is not evaluated at all. Right-associative operator, see `Ocaml_operators[29.65]` for more information.

val (||) : bool -> bool -> bool

The boolean 'or'. Evaluation is sequential, left-to-right: in e1 || e2, e1 is evaluated first, and if it returns true, e2 is not evaluated at all. Right-associative operator, see `Ocaml_operators[29.65]` for more information.

Debugging

val __LOC__ : string

__LOC__ returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d".

Since: 4.02

val __FILE__ : string

__FILE__ returns the name of the file currently being parsed by the compiler.

Since: 4.02

val __LINE__ : int

__LINE__ returns the line number at which this expression appears in the file currently being parsed by the compiler.

Since: 4.02

val __MODULE__ : string

__MODULE__ returns the module name of the file being parsed by the compiler.

Since: 4.02

val __POS__ : string * int * int * int

__POS__ returns a tuple (file, lnum, cnum, enum), corresponding to the location at which this expression appears in the file currently being parsed by the compiler. file is the current filename, lnum the line number, cnum the character position in the line and enum the last character position in the line.

Since: 4.02
`Arg.parse` `speclist` `anon Fun` `usage msg` parses the command line. `speclist` is a list of triples (`key`, `spec`, `doc`). `key` is the option keyword, it must start with a '-' character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon Fun` is called on anonymous arguments. The functions in `spec` and `anon Fun` are called in the same order as their arguments appear on the command line.

If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows:

* The reason for the error: unknown option, invalid or missing argument, etc.

* `usage msg`

* The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list.

For the user to be able to specify anonymous arguments starting with a `-`, include for example (`"-", String anonFun, doc`) in `speclist`.

By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`.

```hcl
val parse_dynamic :
  (key * spec * doc) list ref ->
  anon Fun -> usage msg -> unit
```

Same as `Arg.parse`[28.1], except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form:

* command subcommand `options` where the list of options depends on the value of the subcommand argument.

**Since: 4.01**

```hcl
val parse_argv :
  ?current:int ref ->
  string array ->
  (key * spec * doc) list -> anon Fun -> usage msg -> unit
```

`Arg.parse_argv` ~`current` `args` `speclist` `anon Fun` `usage msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or `Arg.current`[28.1]. You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises `Arg.Bad`[28.1] with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises `Arg.Help`[28.1] with the help message as argument.

```hcl
val parse_argv_dynamic :
  ?current:int ref ->
```
val `__FUNCTION__` : `string`

`__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes.

**Since:** 4.12

val `__LOC_OF__` : `'a -> string * 'a`

`__LOC_OF__ expr` returns a pair (`loc`, `expr`) where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: `"File %S, line %d, characters %d-%d"`.

**Since:** 4.02

val `__LINE_OF__` : `'a -> int * 'a`

`__LINE_OF__ expr` returns a pair (`line`, `expr`), where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler.

**Since:** 4.02

val `__POS_OF__` : `'a -> (string * int * int * int) * 'a`

`__POS_OF__ expr` returns a pair (`loc`, `expr`), where `loc` is a tuple (`file`, `lnum`, `cnum`, `enum`) corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line.

**Since:** 4.02

## Composition operators

val (`|>`) : `'a -> ('a -> 'b) -> 'b`

Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see `Ocaml_operators[29.65]` for more information.

**Since:** 4.01

val (`@@`) : (`'a -> 'b`) -> `'a -> 'b`

Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see `Ocaml_operators[29.65]` for more information.

**Since:** 4.01

## Integer arithmetic

Integers are `Sys.int_size` bits wide. All operations are taken modulo $2^{Sys.int_size}$. They do not fail on overflow.

val (`~`) : `int -> int`

Unary negation. You can also write `- e` instead of `~ e`. Unary operator, see `Ocaml_operators[29.65]` for more information.
```hkl
string array ->
(key * spec * doc) list ref ->
anon Fun -> string -> unit
```

Same as `Arg.parse_argv[28.1]`, except that the `speclist` argument is a reference and may be updated during the parsing. See `Arg.parse_dynamic[28.1]`.

**Since:** 4.01

```hkl
val parse_and_extend_argv_dynamic :
    int ref ->
    string array ref ->
    (key * spec * doc) list ref ->
    anon fun -> string -> unit
```

Same as `Arg.parse_argv_dynamic[28.1]`, except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See `Arg.parse_argv_dynamic[28.1]`.

**Since:** 4.05

```hkl
val parse_extend : (key * spec * doc) list -> anon fun -> usage msg -> unit
```
Same as `Arg.parse[28.1]`, except that the `Expand` arguments are allowed and the `Arg.current[28.1]` reference is not updated.

**Since:** 4.05

### exception Help of string

Raised by `Arg.parse_argv` when the user asks for help.

### exception Bad of string

Functions in `spec` or `anon fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by `Arg.parse_argv[28.1]` in case of an error.

```hkl
val usage : (key * spec * doc) list -> usage msg -> unit
```

`Argocollect` `usage msg` prints to standard error an error message that includes the list of valid options. This is the same message that `Arg.parse[28.1]` prints in case of error. `speclist` and `usage msg` are the same as for `Arg.parse[28.1]`.

```hkl
val usage_string : (key * spec * doc) list -> usage msg -> string
```

Returns the message that would have been printed by `Argocollect` [28.1], if provided with the same parameters.

```hkl
val align :
?limit:int ->
(key * spec * doc) list -> (key * spec * doc) list
```

Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line.
val (+-) : int -> int

Unary addition. You can also write `+ e` instead of `+ e`. Unary operator, see `Ocaml_operators[29.65]` for more information.

Since: 3.12

val succ : int -> int

succ x is x + 1.

val pred : int -> int

pred x is x - 1.

val (+) : int -> int -> int

Integer addition. Left-associative operator, see `Ocaml_operators[29.65]` for more information.

val (-) : int -> int -> int

Integer subtraction. Left-associative operator, see `Ocaml_operators[29.65]` for more information.

val (* ) : int -> int -> int

Integer multiplication. Left-associative operator, see `Ocaml_operators[29.65]` for more information.

val (/) : int -> int -> int

Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(-x) / y = x / (-y) = - (x / y)`. Left-associative operator, see `Ocaml_operators[29.65]` for more information.

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

val (mod) : int -> int -> int

Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division_by_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see `Ocaml_operators[29.65]` for more information.

**Raises** `Division_by_zero` if `y` is zero.

val abs : int -> int

`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.

val max_int : int

The greatest representable integer.

val min_int : int

The smallest representable integer.
val current : int ref

Position (in Sys.argv[28.55]) of the argument being processed. You can change this value, e.g. to force Arg.parse[28.1] to skip some arguments. Arg.parse[28.1] uses the initial value of Arg.current[28.1] as the index of argument 0 (the program name) and starts parsing arguments at the next element.

val read_arg : string -> string array

Arg.read_arg file reads newline-terminated command line arguments from file file.

Since: 4.05

val read_arg0 : string -> string array

Identical to Arg.read_arg[28.1] but assumes null character terminated command line arguments.

Since: 4.05

val write_arg : string -> string array -> unit

Arg.write_arg file args writes the arguments args newline-terminated into the file file.

If any of the arguments in args contains a newline, use Arg.write_arg0[28.1] instead.

Since: 4.05

val write_arg0 : string -> string array -> unit

Identical to Arg.write_arg[28.1] but uses the null character for terminator instead of newline.

Since: 4.05

## 28.2 Module Array : Array operations.

The labeled version of this module can be used as described in the StdLabels[28.52] module.

type 'a t = 'a array

An alias for the type of arrays.

val length : 'a array -> int

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

val get : 'a array -> int -> 'a

get a n returns the element number n of array a. The first element has number 0. The last element has number length a - 1. You can also write a.(n) instead of get a n.

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

val set : 'a array -> int -> 'a -> unit
## Bitwise operations

**val (land) : int -> int -> int**

Bitwise logical and. Left-associative operator, see `Ocaml_operators` [29.65] for more information.

**val (lor) : int -> int -> int**

Bitwise logical or. Left-associative operator, see `Ocaml_operators` [29.65] for more information.

**val (lxor) : int -> int -> int**

Bitwise logical exclusive or. Left-associative operator, see `Ocaml_operators` [29.65] for more information.

**val lnot : int -> int**

Bitwise logical negation.

**val (lsl) : int -> int -> int**

n lsl m shifts n to the left by m bits. The result is unspecified if m < 0 or m > Sys.int_size. Right-associative operator, see `Ocaml_operators` [29.65] for more information.

**val (lsr) : int -> int -> int**

n lsr m shifts n to the right by m bits. This is a logical shift: zeroes are inserted regardless of the sign of n. The result is unspecified if m < 0 or m > Sys.int_size. Right-associative operator, see `Ocaml_operators` [29.65] for more information.

**val (asr) : int -> int -> int**

n asr m shifts n to the right by m bits. This is an arithmetic shift: the sign bit of n is replicated. The result is unspecified if m < 0 or m > Sys.int_size. Right-associative operator, see `Ocaml_operators` [29.65] for more information.

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

**val (~-.) : float -> float**

Unary negation. You can also write -. e instead of ~-. e. Unary operator, see `Ocaml_operators` [29.65] for more information.

**val (+-.) : float -> float**
`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`.

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

`val make : int -> 'a -> 'a array`

`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the value of `x` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.

`val create_float : int -> float array`

`create_float n` returns a fresh float array of length `n`, with uninitialized data.

**Since:** 4.03

`val init : int -> (int -> 'a) -> 'a array`

`init n f` returns a fresh array 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 in order to the integers 0 to `n-1`.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.

`val make_matrix : int -> int -> 'a -> 'a array array`

`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element `(x,y)` of a matrix `m` is accessed with the notation `m.(x).(y)`.

**Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than `Sys.max_array_length[28.55]`. If the value of `e` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.

`val append : 'a array -> 'a array -> 'a array`

`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`.

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

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

Same as `Array.append[28.2]`, but concatenates a list of arrays.

`val sub : 'a array -> int -> int -> 'a array`

`sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `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`.
Unary addition. You can also write `+`. `e` instead of `~+`. `e`. Unary operator, see `Ocaml_operators`[29.65] for more information.

**Since: 3.12**

`val (+.) : float -> float -> float`

Floating-point addition. Left-associative operator, see `Ocaml_operators`[29.65] for more information.

`val (-.) : float -> float -> float`

Floating-point subtraction. Left-associative operator, see `Ocaml_operators`[29.65] for more information.

`val (*.) : float -> float -> float`

Floating-point multiplication. Left-associative operator, see `Ocaml_operators`[29.65] for more information.

`val (/.) : float -> float -> float`

Floating-point division. Left-associative operator, see `Ocaml_operators`[29.65] for more information.

`val (**): float -> float -> float`

Exponentiation. Right-associative operator, see `Ocaml_operators`[29.65] for more information.

`val sqrt : float -> float`

Square root.

`val exp : float -> float`

Exponential.

`val log : float -> float`

Natural logarithm.

`val log10 : float -> float`

Base 10 logarithm.

`val expm1 : float -> float`

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

**Since: 3.12**

`val log1p : float -> float`
`val copy : 'a array -> 'a array`

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

`val fill : 'a array -> int -> int -> 'a -> unit`

fill a pos len x modifies the array 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 : 'a array -> int -> 'a array -> int -> int -> unit`

blit src src_pos dst dst_pos len copies len elements from array src, starting at element number src_pos, to array dst, starting at element number dst_pos. It works correctly even if src and dst are the same array, 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 : 'a array -> 'a list`

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

`val of_list : 'a list -> 'a array`

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

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

## Iterators

`val iter : ('a -> unit) -> 'a array -> 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 -> 'a -> unit) -> 'a array -> unit`

Same as Array.iter[28.2], but the function is applied to the index of the element as first argument, and the element itself as second argument.

`val map : ('a -> 'b) -> 'a array -> 'b array`

map 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_inplace : ('a -> 'a) -> 'a array -> 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 -> 'a -> 'b) -> 'a array -> 'b array`
`log1p x` computes `log(1.0 + . x)` (natural logarithm), giving numerically-accurate results even if x is close to 0.0.

**Since: 3.12**

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

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

**Since: 4.00**

**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**
Same as `Array.map`[28.2], 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 -> 'a -> 'a) -> 'a array -> unit`

Same as `Array.map_inplace`[28.2], 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 -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc`

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

`val fold_left_map :`

(`'acc -> 'a -> 'acc * 'b) -> 'acc -> 'a array -> 'acc * 'b array`

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

**Since:** 4.13

`val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> '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 array `a`.

## Iterators on two arrays

`val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit`

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

**Since:** 4.03 (4.05 in `ArrayLabels`)

**Raises:** `Invalid_argument` if the arrays are not the same size.

`val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array`

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

**Since:** 4.03 (4.05 in `ArrayLabels`)

**Raises:** `Invalid_argument` if the arrays are not the same size.

## Array scanning

`val for_all : ('a -> bool) -> 'a array -> bool`

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

**Since:** 4.03
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 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 abs_float : float -> float**

`abs_float f` returns the absolute value of `f`.

**val copysign : float -> float -> float**

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

Since: 4.00

**val mod_float : float -> float -> float**

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

`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**
val exists : ('a -> bool) -> 'a array -> bool

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

Since: 4.03

val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool

Same as Array.for_all[28.2], but for a two-argument predicate.

Since: 4.11

Raises Invalid_argument if the two arrays have different lengths.

val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool

Same as Array.exists[28.2], but for a two-argument predicate.

Since: 4.11

Raises Invalid_argument if the two arrays have different lengths.

val mem : 'a -> 'a array -> bool

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

Since: 4.03

val memq : 'a -> 'a array -> bool

Same as Array.mem[28.2], but uses physical equality instead of structural equality to compare list elements.

Since: 4.03

val find_opt : ('a -> bool) -> 'a array -> 'a option

find_opt f a returns the first element of the array a that satisfies the predicate f, or None if there is no value that satisfies f in the array a.

Since: 4.13

val find_index : ('a -> bool) -> 'a array -> 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 : ('a -> 'b option) -> 'a array -> 'b option

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

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

`val float : int -> float`

Same as `float_of_int` [28.2].

`val float_of_int : int -> float`

Convert an integer to floating-point.

`val truncate : float -> int`

Same as `int_of_float` [28.2].

`val int_of_float : 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 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 a quiet `NaN` since 5.1; it was a signaling `NaN` before.

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

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

`type fpclass =`

`| FP_normal`

Normal number, none of the below

`| FP_subnormal`
val find_mapi : (int -> 'a -> 'b option) -> 'a array -> '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

Arrays of pairs

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

split [|(a1,b1); ...; (an,bn)|] is ([|a1; ...; an|], [|b1; ...; bn|]).

Since: 4.13

val combine : 'a array -> 'b array -> ('a * 'b) array

combine [|a1; ...; an|] [|b1; ...; bn|] is [[(a1,b1); ...; (an,bn)|]. Raise Invalid_argument if the two arrays have different lengths.

Since: 4.13

Sorting

val sort : ('a -> 'a -> int) -> 'a array -> unit

Sort an array 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[27.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 array 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 and only if i ≥ j

val stable_sort : ('a -> 'a -> int) -> 'a array -> unit

Same as Array.sort[28.2], 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 array of length n/2, where
n is the length of the array. It is usually faster than the current implementation of
Array.sort[28.2].
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 `classify_float` [28.2] function.

### `val classify_float`: `float` -> `fpclass`

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

## String operations

More string operations are provided in module `String` [28.2].

### `val (ˆ)`: `string` -> `string` -> `string`

String concatenation. Right-associative operator, see `Ocaml_operators` [29.65] for more information.

**Raises** `Invalid_argument` if the result is longer than `Sys.max_string_length` [29.60] bytes.

## Character operations

More character operations are provided in module `Char` [28.2].

### `val int_of_char`: `char` -> `int`

Return the ASCII code of the argument.

### `val char_of_int`: `int` -> `char`

Return the character with the given ASCII code.

**Raises** `Invalid_argument` if the argument is outside the range 0-255.

## Unit operations

### `val ignore`: `'a' -> unit`

Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning.
val fast_sort : ('a -> 'a -> int) -> 'a array -> unit
Same as Array.sort[28.2] or Array.stable_sort[28.2], whichever is faster on typical input.

## Arrays and Sequences

val to_seq : 'a array -> 'a Seq.t
Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence.

Since: 4.07

val to_seqi : 'a array -> (int * 'a) Seq.t
Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence.

Since: 4.07

val of_seq : 'a Seq.t -> 'a array
Create an array from the generator

Since: 4.07

## Arrays and concurrency safety

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

## Atomicity

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

let size = 100_000_000
let a = Array.make size 1
let d1 = Domain spawn (fun () ->
  Array.iteri (fun i x -> a.(i) <- x + 1) a
)
let d2 = Domain spawn (fun () ->
  Array.iteri (fun i x -> a.(i) <- 2 * x + 1) a
)
let () = Domain.join d1; Domain.join d2

After executing this code, each field of the 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[28.36]`).
## String conversion functions

**val string_of_bool : bool -> string**

Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly.

**val bool_of_string_opt : string -> bool option**

Convert the given string to a boolean.

Return `None` if the string is not "true" or "false".

**Since: 4.05**

**val bool_of_string : string -> bool**

Same as `bool_of_string_opt[28.2]`, but raise `Invalid_argument "bool_of_string"` instead of returning `None`.

**val string_of_int : int -> string**

Return the string representation of an integer, in decimal.

**val int_of_string_opt : string -> int option**

Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`).

The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds `max_int[28.2]` it is converted to the signed integer `min_int + input - max_int - 1`.

The `_` (underscore) character can appear anywhere in the string and is ignored.

Return `None` 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 `int`.

**Since: 4.05**

**val int_of_string : string -> int**

Same as `int_of_string_opt[28.2]`, but raise `Failure "int_of_string"` instead of returning `None`.

**val string_of_float : 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 `[28.2]`.

**val float_of_string_opt : string -> float option**
## 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 for float arrays).

## Float arrays

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

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

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

## 28.3 Module ArrayLabels : Array operations.

The labeled version of this module can be used as described in the StdLabels[28.52] module.

```python
type 'a t = 'a array
```

An alias for the type of arrays.

```python
val length : 'a array -> int
```

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

```python
val get : 'a array -> int -> 'a
```
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 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.

Return `None` if the given string is not a valid representation of a float.

**Since: 4.05**

`val float_of_string : string -> float`

Same as `float_of_string_opt[28.2]`, but raise `Failure "float_of_string"` instead of returning `None`.

## Pair operations

`val fst : 'a * 'b -> 'a`

Return the first component of a pair.

`val snd : 'a * 'b -> 'b`

Return the second component of a pair.

## List operations

More list operations are provided in module `List[28.2]`.

`val (@) : 'a list -> 'a list -> 'a list`

`10 @ 11` appends 11 to 10. Same function as `List.append[29.33]`. Right-associative operator, see `Ocaml_operators[29.65]` for more information.

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

## Input/output

Note: all input/output functions can raise `Sys_error` when the system calls they invoke fail.

`type in_channel`

The type of input channel.

`type out_channel`
`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`.

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

`val set : 'a array -> int -> 'a -> unit`

`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`.

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

`val make : int -> 'a -> 'a array`

`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the value of `x` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.

`val create_float : int -> float array`

`create_float n` returns a fresh float array of length `n`, with uninitialized data.

**Since:** 4.03

`val init : int -> f:(int -> 'a) -> 'a array`

`init n ~f` returns a fresh array 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 in order to the integers 0 to `n-1`.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.

`val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array`

`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element `(x,y)` of a matrix `m` is accessed with the notation `m.(x).(y)`.

**Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than `Sys.max_array_length[28.55]`. If the value of `e` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.

`val append : 'a array -> 'a array -> 'a array`

`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`.

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

`val concat : 'a array list -> 'a array`
The type of output channel.

`val stdin : in_channel`

The standard input for the process.

`val stdout : out_channel`

The standard output for the process.

`val stderr : out_channel`

The standard error output for the process.

## Output functions on standard output

`val print_char : char -> unit`

Print a character on standard output.

`val print_string : string -> unit`

Print a string on standard output.

`val print_bytes : bytes -> unit`

Print a byte sequence on standard output.

Since: 4.02

`val print_int : int -> unit`

Print an integer, in decimal, on standard output.

`val print_float : float -> unit`

Print a floating-point number, in decimal, on standard output.

The conversion of the number to a string uses `string_of_float[28.2]` and can involve a loss of precision.

`val print_endline : string -> unit`

Print a string, followed by a newline character, on standard output and flush standard output.

`val print_newline : unit -> unit`

Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output.
Same as `ArrayLabels.append[28.3]`, but concatenates a list of arrays.

```ksharp
val sub : 'a array -> pos:int -> len:int -> 'a array
```

sub a ~pos ~len returns a fresh array of length len, containing the elements number pos to pos + len - 1 of array 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.

```ksharp
val copy : 'a array -> 'a array
```

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

```ksharp
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
```

fill a ~pos ~len x modifies the array 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.

```ksharp
val blit :
```

```
src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit
```

blit ~src ~src_pos ~dst ~dst_pos ~len copies len elements from array src, starting at element number src_pos, to array dst, starting at element number dst_pos. It works correctly even if src and dst are the same array, 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.

```ksharp
val to_list : 'a array -> 'a list
```

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

```ksharp
val of_list : 'a list -> 'a array
```

of_list l returns a fresh array containing the elements of l.

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

## Iterators

```ksharp
val iter : f:('a -> unit) -> 'a array -> 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); ().

```ksharp
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
```

Same as `ArrayLabels.iter[28.3]`, but the function is applied to the index of the element as first argument, and the element itself as second argument.

```ksharp
val map : f:('a -> 'b) -> 'a array -> 'b array
```
## Output functions on standard error

* `val prerr_char : char -> unit`

Print a character on standard error.

* `val prerr_string : string -> unit`

Print a string on standard error.

* `val prerr_bytes : bytes -> unit`

Print a byte sequence on standard error.

**Since: 4.02**

* `val prerr_int : int -> unit`

Print an integer, in decimal, on standard error.

* `val prerr_float : float -> unit`

Print a floating-point number, in decimal, on standard error.

The conversion of the number to a string uses `string_of_float[28.2]` and can involve a loss of precision.

* `val prerr_endline : string -> unit`

Print a string, followed by a newline character on standard error and flush standard error.

* `val prerr_newline : unit -> unit`

Print a newline character on standard error, and flush standard error.

## Input functions on standard input

* `val read_line : unit -> string`

Flush standard output, then read characters from standard input until a newline character is encountered.

Return the string of all characters read, without the newline character at the end.

**Raises End_of_file if the end of the file is reached at the beginning of line.**

* `val read_int_opt : unit -> int option`

Flush standard output, then read one line from standard input and convert it to an integer.

Return `None` if the line read is not a valid representation of an integer.

**Since: 4.05**

* `val read_int : unit -> int`

Same as `read_int_opt[28.2]`, but raise `Failure "int_of_string"` instead of returning `None`.
`map ~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_inplace : f:('a -> 'a) -> 'a array -> unit`
`map_inplace ~f a` applies function `f` to all elements of `a`, and updates their values in place.

**Since:** 5.1

`val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array`

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

`val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit`

Same as `ArrayLabels.map_inplace[28.3]`, 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 : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc`
`fold_left ~f ~init a` computes `f (...) (f (f init a.(0)) a.(1)) ... a.(n-1)`, where `n` is the length of the array `a`.

`val fold_left_map :`
`f:('acc -> 'a -> 'acc * 'b) -> init:'acc -> 'a array -> 'acc * 'b array`
`fold_left_map` is a combination of `ArrayLabels.fold_left[28.3]` and `ArrayLabels.map[28.3]` that threads an accumulator through calls to `f`.

**Since:** 4.13

`val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> 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 array `a`.

## Iterators on two arrays

`val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit`
`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`.

**Since:** 4.05

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

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

**Since:** 4.05

**Raises** `Invalid_argument` if the arrays are not the same size.
### `val read_float_opt`: `unit -> float` option

Flush standard output, then read one line from standard input and convert it to a floating-point number.

Return `None` if the line read is not a valid representation of a floating-point number.

**Since: 4.05**

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

Same as `read_float_opt[28.2]`, but raise `Failure "float_of_string"` instead of returning `None`.

## General output functions

### `type open_flag =`

- `Open_rdoonly`
  open for reading.

- `Open_wronly`
  open for writing.

- `Open_append`
  open for appending: always write at end of file.

- `Open_creat`
  create the file if it does not exist.

- `Open_trunc`
  empty the file if it already exists.

- `Open_excl`
  fail if `Open_creat` and the file already exists.

- `Open_binary`
  open in binary mode (no conversion).

- `Open_text`
  open in text mode (may perform conversions).

- `Open_nonblock`
  open in non-blocking mode.

Opening modes for `open_out_gen[28.2]` and `open_in_gen[28.2]`.

### `val open_out`: `string -> out_channel`

Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.
## Array scanning

val `for_all`: `f:('a -> bool) -> 'a array -> bool`
`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`.

**Since:** 4.03

val `exists`: `f:('a -> bool) -> 'a array -> bool`
`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`.

**Since:** 4.03

val `for_all2`: `f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool`
Same as `ArrayLabels.for_all[28.3]`, but for a two-argument predicate.

**Since:** 4.11

**Raises** `Invalid_argument` if the two arrays have different lengths.

val `exists2`: `f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool`
Same as `ArrayLabels.exists[28.3]`, but for a two-argument predicate.

**Since:** 4.11

**Raises** `Invalid_argument` if the two arrays have different lengths.

val `mem`: `'a -> set:'a array -> bool`
`mem a ~set` is true if and only if `a` is structurally equal to an element of `l` (i.e. there is an `x` in `l` such that `compare a x = 0`).

**Since:** 4.03

val `memq`: `'a -> set:'a array -> bool`
Same as `ArrayLabels.mem[28.3]`, but uses physical equality instead of structural equality to compare list elements.

**Since:** 4.03

val `find_opt`: `f:('a -> bool) -> 'a array -> 'a option`
`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`.

**Since:** 4.13

val `find_index`: `f:('a -> bool) -> 'a array -> 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 open_out_bin : string -> out_channel

Same as `open_out[28.2]`, but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like `open_out[28.2]`.

val open_out_gen : open_flag list -> int -> string -> out_channel

`open_out_gen` mode `perm` filename opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. `open_out[28.2]` and `open_out_bin[28.2]` are special cases of this function.

val flush : out_channel -> unit

Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.

val flush_all : unit -> unit

Flush all open output channels; ignore errors.

val output_char : out_channel -> char -> unit

Write the character on the given output channel.

val output_string : out_channel -> string -> unit

Write the string on the given output channel.

val output_bytes : out_channel -> bytes -> unit

Write the byte sequence on the given output channel.

**Since:** 4.02

val output : out_channel -> bytes -> int -> int -> unit

`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`.

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

val output_substring : out_channel -> string -> int -> int -> unit

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

**Since:** 4.02

val output_byte : out_channel -> int -> unit

Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256.

val output_binary_int : out_channel -> int -> unit
val find_map : f:('a -> 'b option) -> 'a array -> 'b option
find_map ~f a applies f to the elements of a in order, and returns the first result of the
form Some v, or None if none exist.

Since: 4.13

val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> '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

Arrays of pairs

val split : ('a * 'b) array -> 'a array * 'b array
split [(a1,b1); ...; (an,bn)] is [[|a1; ...; an|], [|b1; ...; bn|]].

Since: 4.13

val combine : 'a array -> 'b array -> ('a * 'b) array
combine [[a1; ...; an]] [[b1; ...; bn]] is [[(a1,b1); ...; (an,bn)]]. Raise
Invalid_argument if the two arrays have different lengths.

Since: 4.13

Sorting

val sort : cmp:('a -> 'a -> int) -> 'a array -> unit

Sort an array 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[27.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 array 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 and only if `i ≥ j`
Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo $2^{32}$. The only reliable way to read it back is through the `input_binary_int` [28.2] function. The format is compatible across all machines for a given version of OCaml.

val output_value : out_channel -> 'a -> unit

Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function `input_value` [28.2]. See the description of module ` Marshal` [28.2] for more information. `output_value` [28.2] is equivalent to ` Marshal.to_channel` [29.36] with an empty list of flags.

val seek_out : out_channel -> int -> unit

`seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.

val pos_out : out_channel -> int

Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.

val out_channel_length : out_channel -> int

Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.

val close_out : out_channel -> unit

Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys_error` if the operating system signals an error when flushing or closing.

val close_out_noerr : out_channel -> unit

Same as `close_out`, but ignore all errors.

val set_binary_mode_out : out_channel -> bool -> unit

`set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode.
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit

Same as ArrayLabels.sort[28.3], 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 array of length n/2, where n is the length of the array. It is usually faster than the current implementation of ArrayLabels.sort[28.3].

val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit

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

## Arrays and Sequences

val to_seq : 'a array -> 'a Seq.t

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

**Since:** 4.07

val to_seqi : 'a array -> (int * 'a) Seq.t

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

**Since:** 4.07

val of_seq : 'a Seq.t -> 'a array

Create an array from the generator

**Since:** 4.07

## Arrays and concurrency safety

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

## Atomicity

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

```hml
let size = 100_000_000
let a = ArrayLabels.make size 1
let d1 = Domain spawn (fun () ->
```
## General input functions

**val open_in : string -> in_channel**

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

**val open_in_bin : string -> in_channel**

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

**val open_in_gen : open_flag list -> int -> string -> in_channel**

`open_in_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. `open_in[28.2]` and `open_in_bin[28.2]` are special cases of this function.

**val input_char : in_channel -> char**

Read one character from the given input channel.

**Raises** `End_of_file` if there are no more characters to read.

**val input_line : in_channel -> string**

Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end.

**Raises** `End_of_file` if the end of the file is reached at the beginning of line.

**val input : in_channel -> 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. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also `really_input[28.2]` for reading exactly `len` characters.) Exception `Invalid_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`.

**val really_input : in_channel -> bytes -> int -> int -> unit**

`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`.

**Raises**

* `End_of_file` if the end of file is reached before `len` characters have been read.

* `Invalid_argument` if `pos` and `len` do not designate a valid range of `buf`.
```pascal
ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a
)
let d2 = Domain spawn (fun () ->
  ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a
)
let () = Domain.join d1; Domain.join d2
```

After executing this code, each field of the 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[28.36]`).

## 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 for float arrays).

## Float arrays

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

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

the `res` 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 really_input_string : in_channel -> int -> string

really_input_string ic len reads len characters from channel ic and returns them in a
new string.

Since: 4.02

Raises End_of_file if the end of file is reached before len characters have been read.

val input_byte : in_channel -> int

Same as input_char[28.2], but return the 8-bit integer representing the character.

Raises End_of_file if the end of file was reached.

val input_binary_int : in_channel -> int

Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel.
See output_binary_int [28.2].

Raises End_of_file if the end of file was reached while reading the integer.

val input_value : in_channel -> 'a

Read the representation of a structured value, as produced by output_value [28.2], and
return the corresponding value. This function is identical to Marshal.from_channel [29.36];
see the description of module Marshal [28.2] for more information, in particular concerning
the lack of type safety.

val seek_in : in_channel -> int -> unit

seek_in 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_in : in_channel -> int

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 pos_in, then going back to this position using
seek_in will not work. For this programming idiom to work reliably and portably, the file
must be opened in binary mode.

val in_channel_length : in_channel -> int

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 close_in : in_channel -> unit

Close the given channel. Input functions raise a Sys_error exception when they are applied
to a closed input channel, except close_in, which does nothing when applied to an already
closed channel.

val close_in_noerr : in_channel -> unit
## 28.4 Module Atomic: Atomic references.

See the examples[28.44] below. See 'Memory model: The hard bits' chapter in the manual.

**Since:** 4.12

```rust
type !'a t
```

An atomic (mutable) reference to a value of type `'a`.

```rust
val make : 'a -> 'a t
```

Create an atomic reference.

```rust
val get : 'a t -> 'a
```

Get the current value of the atomic reference.

```rust
val set : 'a t -> 'a -> unit
```

Set a new value for the atomic reference.

```rust
val exchange : 'a t -> 'a -> 'a
```

Set a new value for the atomic reference, and return the current value.

```rust
val compare_and_set : 'a t -> 'a -> 'a -> bool
```

compare_and_set `r` seen `v` sets the new value of `r` to `v` only if its current value is physically equal to seen – the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise.

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

fetch_and_add `r` `n` atomically increments the value of `r` by `n`, and returns the current value (before the increment).

```rust
val incr : int t -> unit
```

incr `r` atomically increments the value of `r` by 1.

```rust
val decr : int t -> unit
```

decr `r` atomically decrements the value of `r` by 1.

## Examples

### Basic Thread Coordination

A basic use case is to have global counters that are updated in a thread-safe way, for example to keep some sorts of metrics over IOs performed by the program. Another basic use case is to coordinate the termination of threads in a given program, for example when one thread finds an answer, or when the program is shut down by the user.

Here, for example, we're going to try to find a number whose hash satisfies a basic property. To do that, we'll run multiple threads which will try random numbers until they find one that works.
Same as `close_in`, but ignore all errors.

`val set_binary_mode_in : in_channel -> bool -> unit`

`set_binary_mode_in` `ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out` `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.

## Operations on large files

module LargeFile :

sig

val seek_out : out_channel -> int64 -> unit

val pos_out : out_channel -> int64

val out_channel_length : out_channel -> int64

val seek_in : in_channel -> int64 -> unit

val pos_in : in_channel -> int64

val in_channel_length : in_channel -> int64

end

Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`.

## References

type 'a ref =

{ mutable contents : 'a ; }

The type of references (mutable indirection cells) containing a value of type 'a.

val ref : 'a -> 'a ref

Return a fresh reference containing the given value.

val (!) : 'a ref -> 'a

!`r` returns the current contents of reference `r`. Equivalent to `fun r -> rcontents`. Unary operator, see `Ocaml_operators`[29.65] for more information.

val (:=) : 'a ref -> 'a -> unit
`r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> rcontents <- v`. Right-associative operator, see `Ocaml_operators`[29.65] for more information.

`val incr : int ref -> unit`

Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`.

`val decr : int ref -> unit`

Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`.

## Result type

```hml
type ('a, 'b) result =
| Ok of 'a
| Error of 'b
```

Since: 4.03

## Operations on format strings

Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module `Scanf`[28.2] and to print data with formatted output functions from modules `Formatf`[28.2] and `Format`[28.2].

Format strings are made of three kinds of entities:

* *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print,

* *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument,

* *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output.

There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`.

For more information about conversion specifications and formatting indications available, read the documentation of modules `Scanf`[28.2], `Formatf`[28.2] and `Format`[28.2].

Format strings have a general and highly polymorphic type (`'a, 'b, 'c, 'd, 'e, 'f`) `format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml.

The meaning of format string type parameters is as follows:
one more, or one fewer, element) with the old stack. This is optimistic concurrency: each iteration
of, say, `push stack x` gets the old stack 1, and hopes that by the time it tries to replace 1 with
`x::1`, nobody else has had time to modify the list. If the `compare_and_set` fails it means we were
too optimistic, and must try again.

```fortran
type 'a stack = 'a list Atomic.t

let rec push (stack: _ stack) elt : unit =
    let cur = Atomic.get stack in
    let success = Atomic compare_and_set stack cur (elt :: cur) in
    if not success then
        push stack elt

let rec pop (stack: _ stack) : _ option =
    let cur = Atomic.get stack in
    match cur with
    | [] -> None
    | x :: tail ->
        let success = Atomic compare_and_set stack cur tail in
        if success then Some x
        else pop stack

# let st = Atomic.make []
# push st 1
- : unit = ()
# push st 2
- : unit = ()
# pop st
- : int option = Some 2
# pop st
- : int option = Some 1
# pop st
- : int option = None
```

## 28.5 Module Bigarray : Large, multi-dimensional, numerical arrays.

This module implements multi-dimensional arrays of integers and floating-point numbers, thereafter referred to as 'Bigarrays', to distinguish them from the standard OCaml arrays described in Array[28.2].

The implementation allows efficient sharing of large numerical arrays between OCaml code and C or Fortran numerical libraries.

The main differences between 'Bigarrays' and standard OCaml arrays are as follows:
* 'a is the type of the parameters of the format for formatted output functions (`printf`-style functions); 'a is the type of the values read by the format for formatted input functions (`scanf`-style functions).

* 'b is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`-style functions from module `Printf`[28.2], 'b is typically `out_channel`; for `printf`-style functions from module `Format`[28.2], 'b is typically `Format formatter`[29.23]; for `scanf`-style functions from module `Scanf`[28.2], 'b is typically `Scanf.Scanning.in_channel`[29.52].

Type argument 'b is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion.

* 'c is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`-style functions or to the `kscanf`-style functions.

* 'd is the type of parameters for the `scanf`-style functions.

* 'e is the type of the receiver function for the `scanf`-style functions.

* 'f is the final result type of a formatted input/output function invocation: for the `printf`-style functions, it is typically `unit`; for the `scanf`-style functions, it is typically the result type of the receiver function.

```ocaml
type ('a, 'b, 'c, 'd, 'e, 'f) format6 = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6

type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6

type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4

val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
Converts a format string into a string.
```

```ocaml
val format_of_string :
    ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
    ('a, 'b, 'c, 'd, 'e, 'f) format6

format_of_string s returns a format string read from the string literal s. Note:
format_of_string can not convert a string argument that is not a literal. If you need this
functionality, use the more general Scanf.format_from_string[29.52] function.
```

```ocaml
val (~~) :
    ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
    ('f, 'b, 'c, 'e, 'g, 'h) format6 ->
    ('a, 'b, 'c, 'd, 'g, 'h) format6

f1 ~~ f2 catenates format strings f1 and f2. The result is a format string that behaves as
the concatenation of format strings f1 and f2: in case of formatted output, it accepts
arguments from f1, then arguments from f2; in case of formatted input, it returns results
from f1, then results from f2. Right-associative operator, see Ocaml_operators[29.65] for
more information.
```
* Bigarrays are not limited in size, unlike OCaml arrays. (Normal float arrays are limited to 2,097,151 elements on a 32-bit platform, and normal arrays of other types to 4,194,303 elements.)

* Bigarrays are multi-dimensional. Any number of dimensions between 0 and 16 is supported. In contrast, OCaml arrays are mono-dimensional and require encoding multi-dimensional arrays as arrays of arrays.

* Bigarrays can only contain integers and floating-point numbers, while OCaml arrays can contain arbitrary OCaml data types.

* Bigarrays provide more space-efficient storage of integer and floating-point elements than normal OCaml arrays, in particular because they support 'small' types such as single-precision floats and 8 and 16-bit integers, in addition to the standard OCaml types of double-precision floats and 32 and 64-bit integers.

* The memory layout of Bigarrays is entirely compatible with that of arrays in C and Fortran, allowing large arrays to be passed back and forth between OCaml code and C / Fortran code with no data copying at all.

* Bigarrays support interesting high-level operations that normal arrays do not provide efficiently, such as extracting sub-arrays and 'slicing' a multi-dimensional array along certain dimensions, all without any copying.

Users of this module are encouraged to do `open Bigarray` in their source, then refer to array types and operations via short dot notation, e.g. `Array1.t` or `Array2.sub`.

Bigarrays support all the OCaml ad-hoc polymorphic operations:

* comparisons (`=`, `<>`, `<=`, etc, as well as `compare[27.2]`);

* hashing (module `Hash`);

* and structured input-output (the functions from the ` Marshal[28.34] ` module, as well as ` output_value[27.2] ` and ` input_value[27.2] `).

## Element kinds

Bigarrays can contain elements of the following kinds:

* IEEE single precision (32 bits) floating-point numbers (`Bigarray.float32_elt[28.5]`),

* IEEE double precision (64 bits) floating-point numbers (`Bigarray.float64_elt[28.5]`),

* IEEE single precision (2 * 32 bits) floating-point complex numbers (`Bigarray.complex32_elt[28.5]`),

* IEEE double precision (2 * 64 bits) floating-point complex numbers (`Bigarray.complex64_elt[28.5]`),
## Program termination

```hkl
val exit : int -> 'a
```

Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with `Domain.at_exit[29.14]` are called followed by those registered with `at_exit[28.2]`.

An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception.

```hkl
val at_exit : (unit -> unit) -> unit
```

Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following:

* executes `exit[28.2]`

* terminates, either normally or because of an uncaught exception

* executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first.

## Standard library modules

```hkl
module Arg :
    Arg
```

```hkl
module Array :
    Array
```

```hkl
module ArrayLabels :
    ArrayLabels
```

```hkl
module Atomic :
    Atomic
```

```hkl
module Bigarray :
    Bigarray
```

```hkl
module Bool :
    Bool
```

```hkl
module Buffer :
    Buffer
```

```hkl
module Bytes :
    Bytes
```

```hkl
module BytesLabels :
    BytesLabels
```

```hkl
module Callback :
    Callback
```

```hkl
module Char :
```
* 8-bit integers (signed or unsigned) (`Bigarray.int8_signed_elt`[28.5] or `Bigarray.int8_unsigned_elt`[28.5]),

* 16-bit integers (signed or unsigned) (`Bigarray.int16_signed_elt`[28.5] or `Bigarray.int16_unsigned_elt`[28.5]),

* OCaml integers (signed, 31 bits on 32-bit architectures, 63 bits on 64-bit architectures) (`Bigarray.int_elt`[28.5]),

* 32-bit signed integers (`Bigarray.int32_elt`[28.5]),

* 64-bit signed integers (`Bigarray.int64_elt`[28.5]),

* platform-native signed integers (32 bits on 32-bit architectures, 64 bits on 64-bit architectures) (`Bigarray.nativeint_elt`[28.5]).

Each element kind is represented at the type level by one of the `*_elt` types defined below (defined with a single constructor instead of abstract types for technical injectivity reasons).

```hkl
type float32_elt =
  | Float32_elt

type float64_elt =
  | Float64_elt

type int8_signed_elt =
  | Int8_signed_elt

type int8_unsigned_elt =
  | Int8_unsigned_elt

type int16_signed_elt =
  | Int16_signed_elt

type int16_unsigned_elt =
  | Int16_unsigned_elt

type int32_elt =
  | Int32_elt

type int64_elt =
  | Int64_elt

type int_elt =
  | Int_elt

type nativeint_elt =
  | Nativeint_elt

type complex32_elt =
  | Complex32_elt

type complex64_elt =
  | Complex64_elt

type ('a, 'b) kind =
  | Float32 : (float, float32_elt) kind
  | Float64 : (float, float64_elt) kind
```
Char

module Complex :

Complex

module Condition :

Condition

module Digest :

Digest

module Domain :

Domain

**Alert unstable.** The Domain interface may change in incompatible ways in the future.

module Dynarray :

Dynarray

module Pqueue :

Pqueue

module Effect :

Effect

**Alert unstable.** The Effect interface may change in incompatible ways in the future.

module Either :

Either

module Ephemeron :

Ephemeron

module Filename :

Filename

module Float :

Float

module Format :

Format

module Fun :

Fun

module Gc :

Gc

module Hashtbl :

Hashtbl

module Iarray :

Iarray

module In_channel :

In_channel

module Int :

Int
<table><tr><td>Int8_signed</td><td>(int, int8_signed_elt) kind</td></tr><tr><td>Int8_unsigned</td><td>(int, int8_unsigned_elt) kind</td></tr><tr><td>Int16_signed</td><td>(int, int16_signed_elt) kind</td></tr><tr><td>Int16_unsigned</td><td>(int, int16_unsigned_elt) kind</td></tr><tr><td>Int32</td><td>(int32, int32_elt) kind</td></tr><tr><td>Int64</td><td>(int64, int64_elt) kind</td></tr><tr><td>Int</td><td>(int, int_elt) kind</td></tr><tr><td>Nativeint</td><td>(nativeint, nativeint_elt) kind</td></tr><tr><td>Complex32</td><td>(Complex.t, complex32_elt) kind</td></tr><tr><td>Complex64</td><td>(Complex.t, complex64_elt) kind</td></tr><tr><td>Char</td><td>(char, int8_unsigned_elt) kind</td></tr></table>

To each element kind is associated an OCaml type, which is the type of OCaml values that can be stored in the Bigarray or read back from it. This type is not necessarily the same as the type of the array elements proper: for instance, a Bigarray whose elements are of kind `float32_elt` contains 32-bit single precision floats, but reading or writing one of its elements from OCaml uses the OCaml type `float`, which is 64-bit double precision floats.

The GADT type ('a, 'b) kind captures this association of an OCaml type 'a for values read or written in the Bigarray, and of an element kind 'b which represents the actual contents of the Bigarray. Its constructors list all possible associations of OCaml types with element kinds, and are re-exported below for backward-compatibility reasons.

Using a generalized algebraic datatype (GADT) here allows writing well-typed polymorphic functions whose return type depend on the argument type, such as:

```hl
let zero : type a b. (a, b) kind -> a = function
| Float32 -> 0.0 | Complex32 -> Complex.zero
| Float64 -> 0.0 | Complex64 -> Complex.zero
| Int8_signed -> 0 | Int8_unsigned -> 0
| Int16_signed -> 0 | Int16_unsigned -> 0
| Int32 -> 01 | Int64 -> 0L
| Int -> 0 | Nativeint -> 0n
| Char -> '\000'
```

val float32 : (float, float32_elt) kind
See Bigarray char [28.5].

val float64 : (float, float64_elt) kind
See Bigarray char [28.5].

val complex32 : (Complex.t, complex32_elt) kind
See Bigarray char [28.5].

val complex64 : (Complex.t, complex64_elt) kind
See Bigarray char [28.5].
module Int32 :

Int32

module Int64 :

Int64

module Lazy :

Lazy

module Lexing :

Lexing

module List :

List

module ListLabels :

ListLabels

module Map :

Map

module Marshal :

Marshal

module MoreLabels :

MoreLabels

module Mutex :

Mutex

module Nativeint :

Nativeint

module Obj :

Obj

module Oo :

Oo

module Option :

Option

module Out_channel :

Out_channel

module Pair :

Pair

module Parsing :

Parsing

module Printexc :

Printexc

module Printf :

Printf

module Queue :

Queue

module Random :
val int8_signed : (int, int8_signed_elt) kind
  See `Bigarray char` [28.5].

val int8_unsigned : (int, int8_unsigned_elt) kind
  See `Bigarray char` [28.5].

val int16_signed : (int, int16_signed_elt) kind
  See `Bigarray char` [28.5].

val int16_unsigned : (int, int16_unsigned_elt) kind
  See `Bigarray char` [28.5].

val int : (int, int_elt) kind
  See `Bigarray char` [28.5].

val int32 : (int32, int32_elt) kind
  See `Bigarray char` [28.5].

val int64 : (int64, int64_elt) kind
  See `Bigarray char` [28.5].

val nativeint : (nativeint, nativeint_elt) kind
  See `Bigarray char` [28.5].

val char : (char, int8_unsigned_elt) kind
  As shown by the types of the values above, Bigarrays of kind `float32_elt` and `float64_elt` are accessed using the OCaml type `float`. Bigarrays of complex kinds `complex32_elt`, `complex64_elt` are accessed with the OCaml type `Complex.t` [28.12]. Bigarrays of integer kinds are accessed using the smallest OCaml integer type large enough to represent the array elements: `int` for 8- and 16-bit integer Bigarrays, as well as OCaml-integer Bigarrays; `int32` for 32-bit integer Bigarrays; `int64` for 64-bit integer Bigarrays; and `nativeint` for platform-native integer Bigarrays. Finally, Bigarrays of kind `int8_unsigned_elt` can also be accessed as arrays of characters instead of arrays of small integers, by using the kind value `char` instead of `int8_unsigned`.

val kind_size_in_bytes : ('a, 'b) kind -> int
  `kind_size_in_bytes k` is the number of bytes used to store an element of type `k`.
  **Since:** 4.03
Random

module Result :

Result

module Repr :

Repr

module Scanf :

Scanf

module Semaphore :

Semaphore

module Seq :

Seq

module Set :

Set

module Stack :

Stack

module StdLabels :

StdLabels

module String :

String

module StringLabels :

StringLabels

module Sys :

Sys

module Type :

Type

module Uchar :

Uchar

module Unit :

Unit

module Weak :

Weak
## Array layouts

```fortran
type c_layout =
  | C_layout Typ

  See Bigarray.fortran_layout[28.5].
```

```fortran
type fortran_layout =
  | Fortran_layout Typ
```

To facilitate interoperability with existing C and Fortran code, this library supports two different memory layouts for Bigarrays, one compatible with the C conventions, the other compatible with the Fortran conventions.

In the C-style layout, array indices start at 0, and multi-dimensional arrays are laid out in row-major format. That is, for a two-dimensional array, all elements of row 0 are contiguous in memory, followed by all elements of row 1, etc. In other terms, the array elements at (x,y) and (x, y+1) are adjacent in memory.

In the Fortran-style layout, array indices start at 1, and multi-dimensional arrays are laid out in column-major format. That is, for a two-dimensional array, all elements of column 0 are contiguous in memory, followed by all elements of column 1, etc. In other terms, the array elements at (x,y) and (x+1, y) are adjacent in memory.

Each layout style is identified at the type level by the phantom types `Bigarray.c_layout`[28.5] and `Bigarray.fortran_layout`[28.5] respectively.

## Supported layouts

The GADT type `'a layout'` represents one of the two supported memory layouts: C-style or Fortran-style. Its constructors are re-exported as values below for backward-compatibility reasons.

```fortran
type 'a layout =
  | C_layout : c_layout layout
  | Fortran_layout : fortran_layout layout

val c_layout : c_layout layout
val fortran_layout : fortran_layout layout
```

## Generic arrays (of arbitrarily many dimensions)

```python
module Genarray :
  sig
    type (!'a, !'b, !'c) t
```

The type `Genarray.t` is the type of Bigarrays with variable numbers of dimensions. Any number of dimensions between 0 and 16 is supported.

The three type parameters to `Genarray.t` identify the array element kind and layout, as follows:
* the first parameter, `'a'`, is the OCaml type for accessing array elements (`float`, `int`, `int32`, `int64`, `nativeint`);

* the second parameter, `'b'`, is the actual kind of array elements (`float32_elt`, `float64_elt`, `int8_signed_elt`, `int8_unsigned_elt`, etc);

* the third parameter, `'c'`, identifies the array layout (`c_layout` or `fortran_layout`).

For instance, (`float`, `float32_elt`, `fortran_layout`) `Genarray.t` is the type of generic Bigarrays containing 32-bit floats in Fortran layout; reads and writes in this array use the OCaml type `float`.

``` OCaml
val create :
    ('a, 'b) Bigarray.kind ->
    'c Bigarraylayout -> int array -> ('a, 'b, 'c) t
```

`Genarray.create kind layout dimensions` returns a new Bigarray whose element kind is determined by the parameter `kind` (one of `float32`, `float64`, `int8 signed`, etc) and whose layout is determined by the parameter `layout` (one of `c layout` or `fortran layout`). The `dimensions` parameter is an array of integers that indicate the size of the Bigarray in each dimension. The length of `dimensions` determines the number of dimensions of the Bigarray.

For instance, `Genarray.create int32 c layout [14;6;8]` returns a fresh Bigarray of 32-bit integers, in C layout, having three dimensions, the three dimensions being 4, 6 and 8 respectively.

Bigarrays returned by `Genarray.create` are not initialized: the initial values of array elements is unspecified.

`Genarray.create` raises `Invalid_argument` if the number of dimensions is not in the range 0 to 16 inclusive, or if one of the dimensions is negative.

``` OCaml
val init :
    ('a, 'b) Bigarray.kind ->
    'c Bigarraylayout ->
    int array -> (int array -> 'a) -> ('a, 'b, 'c) t
```

`Genarray.init kind layout dimensions f` returns a new Bigarray `b` whose element kind is determined by the parameter `kind` (one of `float32`, `float64`, `int8 signed`, etc) and whose layout is determined by the parameter `layout` (one of `c layout` or `fortran layout`). The `dimensions` parameter is an array of integers that indicate the size of the Bigarray in each dimension. The length of `dimensions` determines the number of dimensions of the Bigarray.

Each element `Genarray.get b i` is initialized to the result of `f i`. In other words, `Genarray.init kind layout dimensions f` tabulates the results of `f` applied to the indices of a new Bigarray whose layout is described by `kind`, `layout` and `dimensions`. The index array `i` may be shared and mutated between calls to `f`.

For instance, `Genarray.init int c layout [12; 1; 3]` (`Array.fold_left (+) 0`) returns a fresh Bigarray of integers, in C layout, having three dimensions (2, 1, 3, respectively), with the element values 0, 1, 2, 1, 2, 3.
# Chapter 29

## The standard library

This chapter describes the functions provided by the OCaml standard library. The modules from the standard library are automatically linked with the user's object code files by the `ocamlc` command. Hence, these modules can be used in standalone programs without having to add any `.cmo` file on the command line for the linking phase. Similarly, in interactive use, these globals can be used in toplevel phrases without having to load any `.cmo` file in memory.

Unlike the core `Stdlib` module, submodules are not automatically “opened” when compilation starts, or when the toplevel system is launched. Hence it is necessary to use qualified identifiers to refer to the functions provided by these modules, or to add `open` directives.

### Conventions

For easy reference, the modules are listed below in alphabetical order of module names. For each module, the declarations from its signature are printed one by one in typewriter font, followed by a short comment. All modules and the identifiers they export are indexed at the end of this report.

### Overview

Here is a short listing, by theme, of the standard library modules.
`Genarray.init` raises `Invalid_argument` if the number of dimensions is not in the range 0 to 16 inclusive, or if one of the dimensions is negative.

Since: 4.12

`val num_dim : ('a, 'b, 'c) t -> int`

Return the number of dimensions of the given `Bigarray`.

`val dim : ('a, 'b, 'c) t -> int array`

`Genarray.dims` a returns all dimensions of the `Bigarray a`, as an array of integers of length `Genarray.num_dim` a.

`val nth_dim : ('a, 'b, 'c) t -> int -> int`

`Genarray.nth_dim` a n returns the n-th dimension of the `Bigarray a`. The first dimension corresponds to n = 0; the second dimension corresponds to n = 1; the last dimension, to n = `Genarray.num_dim` a - 1.

Raises `Invalid_argument` if n is less than 0 or greater or equal than `Genarray.num_dim` a.

`val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind`

Return the kind of the given `Bigarray`.

`val layout : ('a, 'b, 'c) t -> 'c Bigarraylayout`

Return the layout of the given `Bigarray`.

`val change_layout : ('a, 'b, 'c) t -> 'd Bigarraylayout -> ('a, 'b, 'd) t`

`Genarray.change_layout` a layout returns a `Bigarray` with the specified layout, sharing the data with a (and hence having the same dimensions as a). No copying of elements is involved: the new array and the original array share the same storage space. The dimensions are reversed, such that `get v [| a; b |]` in C layout becomes `get v [| b+1; a+1 |]` in Fortran layout.

Since: 4.04

`val size_in_bytes : ('a, 'b, 'c) t -> int`

`size_in_bytes` a is the number of elements in a multiplied by a's `Bigarray.kind_size_in_bytes`[28.5].

Since: 4.03

`val get : ('a, 'b, 'c) t -> int array -> 'a`
## Data structures:

<table><tr><td>String</td><td>p. 917</td><td>string operations</td></tr><tr><td>Bytes</td><td>p. 609</td><td>operations on byte sequences</td></tr><tr><td>Array</td><td>p. 560</td><td>array operations</td></tr><tr><td>List</td><td>p. 784</td><td>list operations</td></tr><tr><td>StdLabels</td><td>p. 917</td><td>labelized versions of the above 4 modules</td></tr><tr><td>Unit</td><td>p. 951</td><td>unit values</td></tr><tr><td>Bool</td><td>p. 602</td><td>boolean values</td></tr><tr><td>Char</td><td>p. 637</td><td>character operations</td></tr><tr><td>Uchar</td><td>p. 948</td><td>Unicode characters</td></tr><tr><td>Int</td><td>p. 767</td><td>integer values</td></tr><tr><td>Option</td><td>p. 846</td><td>option values</td></tr><tr><td>Pair</td><td>p. 852</td><td>pairs of values</td></tr><tr><td>Result</td><td>p. 881</td><td>result values</td></tr><tr><td>Effect</td><td>p. 669</td><td>effect handlers</td></tr><tr><td>Either</td><td>p. 671</td><td>either values</td></tr><tr><td>Hashtbl</td><td>p. 750</td><td>hash tables and hash functions</td></tr><tr><td>Random</td><td>p. 875</td><td>pseudo-random number generator</td></tr><tr><td>Set</td><td>p. 906</td><td>sets over ordered types</td></tr><tr><td>Map</td><td>p. 802</td><td>association tables over ordered types</td></tr><tr><td>MoreLabels</td><td>p. 813</td><td>labelized versions of Hashtbl, Set, and Map</td></tr><tr><td>Oo</td><td>p. 845</td><td>useful functions on objects</td></tr><tr><td>Stack</td><td>p. 915</td><td>last-in first-out stacks</td></tr><tr><td>Queue</td><td>p. 871</td><td>first-in first-out queues</td></tr><tr><td>Pqueue</td><td>p. 854</td><td>priority queues</td></tr><tr><td>Buffer</td><td>p. 604</td><td>buffers that grow on demand</td></tr><tr><td>Dynarray</td><td>p. 652</td><td>dynamic arrays: arrays that grow on demand</td></tr><tr><td>Seq</td><td>p. 893</td><td>functional iterators</td></tr><tr><td>Lazy</td><td>p. 779</td><td>delayed evaluation</td></tr><tr><td>Weak</td><td>p. 952</td><td>references that don't prevent objects from being garbage-collected</td></tr><tr><td>Atomic</td><td>p. 576</td><td>atomic references (for compatibility with concurrent runtimes)</td></tr><tr><td>Ephemeron</td><td>p. 673</td><td>ephemerons and weak hash tables</td></tr><tr><td>Bigarray</td><td>p. 580</td><td>large, multi-dimensional, numerical arrays</td></tr><tr><td>Iarray</td><td>p. 664</td><td>immutable arrays</td></tr></table>

## Arithmetic:

<table><tr><td>Complex</td><td>p. 641</td><td>complex numbers</td></tr><tr><td>Float</td><td>p. 684</td><td>floating-point numbers</td></tr><tr><td>Int32</td><td>p. 770</td><td>operations on 32-bit integers</td></tr><tr><td>Int64</td><td>p. 774</td><td>operations on 64-bit integers</td></tr><tr><td>Nativeint</td><td>p. 841</td><td>operations on platform-native integers</td></tr></table>
Read an element of a generic `Bigarray`. `Genarray.get` `[|i1; ...; iN|]` returns the element of `a` whose coordinates are `i1` in the first dimension, `i2` in the second dimension, ..., `iN` in the N-th dimension.

If `a` has C layout, the coordinates must be greater or equal than 0 and strictly less than the corresponding dimensions of `a`. If `a` has Fortran layout, the coordinates must be greater or equal than 1 and less or equal than the corresponding dimensions of `a`.

If $N > 3$, alternate syntax is provided: you can write `a.{i1, i2, ..., iN}` instead of `Genarray.get` `[|i1; ...; iN|]`. (The syntax `a.{...}` with one, two or three coordinates is reserved for accessing one-, two- and three-dimensional arrays as described below.)

**Raises** `Invalid_argument` if the array `a` does not have exactly `N` dimensions, or if the coordinates are outside the array bounds.

`val set: ('a, 'b, 'c') t -> int array -> 'a -> unit`

Assign an element of a generic `Bigarray`. `Genarray.set` `[|i1; ...; iN|] v` stores the value `v` in the element of `a` whose coordinates are `i1` in the first dimension, `i2` in the second dimension, ..., `iN` in the N-th dimension.

The array `a` must have exactly `N` dimensions, and all coordinates must lie inside the array bounds, as described for `Genarray.get`; otherwise, `Invalid_argument` is raised.

If $N > 3$, alternate syntax is provided: you can write `a.{i1, i2, ..., iN} <- v` instead of `Genarray.set` `[|i1; ...; iN|] v`. (The syntax `a.{...}` <- `v` with one, two or three coordinates is reserved for updating one-, two- and three-dimensional arrays as described below.)

`val sub_left: ('a, 'b, Bigarray.c_layout) t -> int -> int -> ('a, 'b, Bigarray.c_layout) t`

Extract a sub-array of the given `Bigarray` by restricting the first (left-most) dimension. `Genarray.sub_left` `a` `ofs` `len` returns a `Bigarray` with the same number of dimensions as `a`, and the same dimensions as `a`, except the first dimension, which corresponds to the interval `[ofs ... ofs + len - 1]` of the first dimension of `a`. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates `[|i1; ...; iN|]` of the sub-array is identical to the element at coordinates `[|i1+ofs; ...; iN|]` of the original array `a`.

`Genarray.sub_left` applies only to `Bigarrays` in C layout.

**Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid sub-array of `a`, that is, if `ofs < 0`, or `len < 0`, or `ofs + len > Genarray.nth_dim` a 0.

`val sub_right: ('a, 'b, Bigarray.fortran_layout) t -> int -> int -> ('a, 'b, Bigarray.fortran_layout) t`

Extract a sub-array of the given `Bigarray` by restricting the last (right-most) dimension. `Genarray.sub_right` `a` `ofs` `len` returns a `Bigarray` with the same number of
input/output:

<table><tr><td>In_channel</td><td>p. 762</td><td>input channels</td></tr><tr><td>Out_channel</td><td>p. 847</td><td>output channels</td></tr><tr><td>Format</td><td>p. 707</td><td>pretty printing with automatic indentation and line breaking</td></tr><tr><td> Marshal</td><td>p. 810</td><td>marshaling of data structures</td></tr><tr><td> Printf</td><td>p. 867</td><td>formatting printing functions</td></tr><tr><td>Scanf</td><td>p. 884</td><td>formatted input functions</td></tr><tr><td> Digest</td><td>p. 648</td><td>MD5 message digest</td></tr></table>

Parsing:

<table><tr><td>Lexing</td><td>p. 781</td><td>the run-time library for lexers generated by ocamllex</td></tr><tr><td>Parsing</td><td>p. 853</td><td>the run-time library for parsers generated by ocamlyacc</td></tr></table>

System interface:

<table><tr><td>Arg</td><td>p. 555</td><td>parsing of command line arguments</td></tr><tr><td>Callback</td><td>p. 636</td><td>registering OCaml functions to be called from C</td></tr><tr><td>Filename</td><td>p. 680</td><td>operations on file names</td></tr><tr><td>Gc</td><td>p. 740</td><td>memory management control and statistics</td></tr><tr><td>Printexc</td><td>p. 860</td><td>a catch-all exception handler</td></tr><tr><td>Sys</td><td>p. 936</td><td>system interface</td></tr></table>

Multicore interface:

<table><tr><td>Domain</td><td>p. 645</td><td>domain spawn and join</td></tr><tr><td>Mutex</td><td>p. 840</td><td>mutual exclusion locks</td></tr><tr><td>Condition</td><td>p. 643</td><td>condition variables</td></tr><tr><td>Semaphore</td><td>p. 913</td><td>semaphores</td></tr><tr><td>Effect</td><td>p. 669</td><td>deep and shallow effect handlers</td></tr></table>

Misc:

<table><tr><td>Fun</td><td>p. 735</td><td>function values</td></tr><tr><td>Type</td><td>p. 946</td><td>type introspection</td></tr><tr><td>Repr</td><td>p. 880</td><td>functions defined on the low-level representation of values</td></tr></table>

29.1 Module Arg : Parsing of command line arguments.

This module provides a general mechanism for extracting options and arguments from the command line to the program. For example:

```
let usage_msg = "append [-verbose] <file1> [<file2>] ... -o <output>"
let verbose = ref false
let input_files = ref []
let output_file = ref ""
```
dimensions as a, and the same dimensions as a, except the last dimension, which corresponds to the interval `[ofs ... ofs + len - 1]` of the last dimension of a. No copying of elements is involved: the sub-array and the original array share the same storage space. In other terms, the element at coordinates `[|i1; ...; iN|]` of the sub-array is identical to the element at coordinates `[|i1; ...; iN+ofs|]` of the original array a.

`Genarray.sub_right` applies only to Bigarrays in Fortran layout.

**Raises** `Invalid_argument` if `ofs` and `len` do not designate a valid sub-array of a, that is, if `ofs < 1`, or `len < 0`, or `ofs + len > Genarray.nth_dim` a (`Genarray.num_dims` a - 1).

```hcl
val slice_left :
    ('a, 'b, Bigarray.c_layout) t ->
    int array -> ('a, 'b, Bigarray.c_layout) t
```

Extract a sub-array of lower dimension from the given Bigarray by fixing one or several of the first (left-most) coordinates. `Genarray.slice_left` a `[|i1; ... ; iM|]` returns the 'slice' of a obtained by setting the first M coordinates to `i1`, ..., `iM`. If a has N dimensions, the slice has dimension `N - M`, and the element at coordinates `[|j1; ...; j(N-M)|]` in the slice is identical to the element at coordinates `[|i1; ...; iM; j1; ...; j(N-M)|]` in the original array a. No copying of elements is involved: the slice and the original array share the same storage space.

`Genarray.slice_left` applies only to Bigarrays in C layout.

**Raises** `Invalid_argument` if `M >= N`, or if `[|i1; ... ; iM|]` is outside the bounds of a.

```hcl
val slice_right :
    ('a, 'b, Bigarray.fortran_layout) t ->
    int array -> ('a, 'b, Bigarray.fortran_layout) t
```

Extract a sub-array of lower dimension from the given Bigarray by fixing one or several of the last (right-most) coordinates. `Genarray.slice_right` a `[|i1; ... ; iM|]` returns the 'slice' of a obtained by setting the last M coordinates to `i1`, ..., `iM`. If a has N dimensions, the slice has dimension `N - M`, and the element at coordinates `[|j1; ...; j(N-M)|]` in the slice is identical to the element at coordinates `[|j1; ...; j(N-M); i1; ...; iM|]` in the original array a. No copying of elements is involved: the slice and the original array share the same storage space.

`Genarray.slice_right` applies only to Bigarrays in Fortran layout.

**Raises** `Invalid_argument` if `M >= N`, or if `[|i1; ... ; iM|]` is outside the bounds of a.

```hcl
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```

Copy all elements of a Bigarray in another Bigarray. `Genarray.blit` src dst copies all elements of src into dst. Both arrays src and dst must have the same number of dimensions and equal dimensions. Copying a sub-array of src to a sub-array of dst can be achieved by applying `Genarray.blit` to sub-array or slices of src and dst.
```h
val fill : ('a, 'b, 'c) t -> 'a -> unit
```

Set all elements of a `Bigarray` to a given value. `Genarray.fill` a `v` stores the value `v` in all elements of the `Bigarray a`. Setting only some elements of `a` to `v` can be achieved by applying `Genarray.fill` to a sub-array or a slice of `a`.

end

## Zero-dimensional arrays

```h
module Array0 :
```

```h
sig
```

```h
type (!'a, !'b, !'c) t
```

The type of zero-dimensional `Bigarray`s whose elements have OCaml type `'a`, representation kind `'b`, and memory layout `'c`.

```h
val create : ('a, 'b) Bigarray.kind ->
```

```h
'c Bigarraylayout -> ('a, 'b, 'c) t
```

`Array0.create kind layout` returns a new `Bigarray` of zero dimension. `kind` and `layout` determine the array element kind and the array layout as described for `Bigarray.Genarray.create[28.5]`.

```h
val init :
```

```h
('a, 'b) Bigarray.kind ->
```

```h
'c Bigarraylayout -> 'a -> ('a, 'b, 'c) t
```

`Array0.init kind layout` `v` behaves like `Array0.create kind layout` except that the element is additionally initialized to the value `v`.

**Since:** 4.12

```h
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```

Return the kind of the given `Bigarray`.

```h
val layout : ('a, 'b, 'c) t -> 'c Bigarraylayout
```

Return the layout of the given `Bigarray`.

```h
val change_layout : ('a, 'b, 'c) t ->
```

```h
'd Bigarraylayout -> ('a, 'b, 'd) t
```

`Array0.change_layout` a `layout` returns a `Bigarray` with the specified `layout`, sharing the data with `a`. No copying of elements is involved: the new array and the original array share the same storage space.

**Since:** 4.06
val size_in_bytes : ('a, 'b, 'c) t -> int
size_in_bytes a is a's Bigarray.kind_size_in_bytes[28.5].

val get : ('a, 'b, 'c) t -> 'a
Array0.get a returns the only element in a.

val set : ('a, 'b, 'c) t -> 'a -> unit
Array0.set a x v stores the value v in a.

val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
Copy the first Bigarray to the second Bigarray. See Bigarray.Genarray.blit[28.5] for
more details.

val fill : ('a, 'b, 'c) t -> 'a -> unit
Fill the given Bigarray with the given value. See Bigarray.Genarray.fill[28.5] for
more details.

val of_value :
('a, 'b) Bigarray.kind ->
'c Bigarraylayout -> 'a -> ('a, 'b, 'c) t

Build a zero-dimensional Bigarray initialized from the given value.

end

Zero-dimensional arrays. The Array0 structure provides operations similar to those of
Bigarray.Genarray[28.5], but specialized to the case of zero-dimensional arrays that only
contain a single scalar value. Statically knowing the number of dimensions of the array allows
faster operations, and more precise static type-checking.

Since: 4.05

One-dimensional arrays

module Array1 :
sig
type (!'a, !'b, !'c) t

The type of one-dimensional Bigarrays whose elements have OCaml type 'a,
representation kind 'b, and memory layout 'c.

val create :
('a, 'b) Bigarray.kind ->
'c Bigarraylayout -> int -> ('a, 'b, 'c) t
`Arg.parse` `speclist` `anon Fun` `usage msg` parses the command line. `speclist` is a list of triples (`key`, `spec`, `doc`). `key` is the option keyword, it must start with a '-' character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon Fun` is called on anonymous arguments. The functions in `spec` and `anon Fun` are called in the same order as their arguments appear on the command line.

If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows:

* The reason for the error: unknown option, invalid or missing argument, etc.

* `usage msg`

* The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list.

For the user to be able to specify anonymous arguments starting with a `-`, include for example (`"-", String anonFun, doc`) in `speclist`.

By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`.

```hcl
val parse_dynamic :
  (key * spec * doc) list ref ->
  anon Fun -> usage msg -> unit
```

Same as `Arg.parse`[29.1], except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form:

* command subcommand `options` where the list of options depends on the value of the subcommand argument.

**Since: 4.01**

```hcl
val parse_argv :
  ?current:int ref ->
  string array ->
  (key * spec * doc) list -> anon Fun -> usage msg -> unit
```

`Arg.parse_argv` ~`current` `args` `speclist` `anon Fun` `usage msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or `Arg.current`[29.1]. You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises `Arg.Bad`[29.1] with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises `Arg.Help`[29.1] with the help message as argument.

```hcl
val parse_argv_dynamic :
  ?current:int ref ->
```
`Array1.create kind layout dim` returns a new `Bigarray` of one dimension, whose size is `dim`. `kind` and `layout` determine the array element kind and the array layout as described for `Bigarray.Genarray.create` [28.5].

```k
val init : 
    ('a, 'b) Bigarray.kind ->
    'c Bigarraylayout -> int -> (int -> 'a) -> ('a, 'b, 'c) t
```

`Array1.init kind layout dim f` returns a new `Bigarray` `b` of one dimension, whose size is `dim`. `kind` and `layout` determine the array element kind and the array layout as described for `Bigarray.Genarray.create` [28.5].

Each element `Array1.get b i` of the array is initialized to the result of `f i`.

In other words, `Array1.init kind layout dimensions f` tabulates the results of `f` applied to the indices of a new `Bigarray` whose layout is described by `kind`, `layout` and `dim`.

**Since:** 4.12

```k
val dim : ('a, 'b, 'c) t -> int
```

Return the size (dimension) of the given one-dimensional `Bigarray`.

```k
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```

Return the kind of the given `Bigarray`.

```k
val layout : ('a, 'b, 'c) t -> 'c Bigarraylayout
```

Return the layout of the given `Bigarray`.

```k
val change_layout : ('a, 'b, 'c) t ->
    'd Bigarraylayout -> ('a, 'b, 'd) t
```

`Array1.change_layout` returns a `Bigarray` with the specified `layout`, sharing the data with `a` (and hence having the same dimension as `a`). No copying of elements is involved: the new array and the original array share the same storage space.

**Since:** 4.06

```k
val size_in_bytes : ('a, 'b, 'c) t -> int
```

`size_in_bytes` `a` is the number of elements in `a` multiplied by `a`'s `Bigarray.kind_size_in_bytes` [28.5].

**Since:** 4.03

```k
val get : ('a, 'b, 'c) t -> int -> 'a
```

`Array1.get` a `x`, or alternatively `a.{x}`, returns the element of `a` at index `x`. `x` must be greater or equal than 0 and strictly less than `Array1.dim a` if `a` has C layout. If `a` has Fortran layout, `x` must be greater or equal than 1 and less or equal than `Array1.dim a`. Otherwise, `Invalid_argument` is raised.
string array ->
(key * spec * doc) list ref ->
anon fun -> string -> unit

Same as Arg.parse_argv[29.1], except that the `speclist` argument is a reference and may be updated during the parsing. See Arg.parse_dynamic[29.1].

**Since:** 4.01

val parse_and_extend_argv_dynamic :

int ref ->
string array ref ->
(key * spec * doc) list ref ->
anon fun -> string -> unit

Same as Arg.parse_argv_dynamic[29.1], except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See Arg.parse_argv_dynamic[29.1].

**Since:** 4.05

val parse_extend : (key * spec * doc) list -> anon fun -> usage msg -> unit

Same as Arg.parse[29.1], except that the `Expand` arguments are allowed and the `Arg.current[29.1]` reference is not updated.

**Since:** 4.05

exception Help of string

Raised by `Arg.parse_argv` when the user asks for help.

exception Bad of string

Functions in `spec` or `anon fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by `Arg.parse_argv[29.1]` in case of an error.

val usage : (key * spec * doc) list -> usage msg -> unit

`Argocollect usage msg` prints to standard error an error message that includes the list of valid options. This is the same message that `Arg.parse[29.1]` prints in case of error. `speclist` and `usage msg` are the same as for `Arg.parse[29.1]`.

val usage_string : (key * spec * doc) list -> usage msg -> string

Returns the message that would have been printed by `Arg-Collect[29.1]`, if provided with the same parameters.

val align :

?limit:int ->
(key * spec * doc) list -> (key * spec * doc) list

Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line.
```kotlin
val set: ('a, 'b, 'c) t -> int -> 'a -> unit
```

`Array1.set` `a` `x` `v`, also written `a.{x}` `<- v`, stores the value `v` at index `x` in `a`. `x` must be inside the bounds of `a` as described in `Bigarray Array1`. `get[28.5]`; otherwise, `Invalid_argument` is raised.

```kotlin
val sub: ('a, 'b, 'c) t ->
    int -> int -> ('a, 'b, 'c) t
```

Extract a sub-array of the given one-dimensional Bigarray. See `Bigarray.Genarray.sub_left[28.5]` for more details.

```kotlin
val slice: ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) Bigarray Array0.t
```

Extract a scalar (zero-dimensional slice) of the given one-dimensional Bigarray. The integer parameter is the index of the scalar to extract. See `Bigarray.Genarray.slice_left[28.5]` and `Bigarray.Genarray.slice_right[28.5]` for more details.

Since: 4.05

```kotlin
val blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```

Copy the first Bigarray to the second Bigarray. See `Bigarray.Genarray.blit[28.5]` for more details.

```kotlin
val fill: ('a, 'b, 'c) t -> 'a -> unit
```

Fill the given Bigarray with the given value. See `Bigarray.Genarray.fill[28.5]` for more details.

```kotlin
val of_array: 
    ('a, 'b) Bigarray.kind ->
    'c Bigarraylayout -> 'a array -> ('a, 'b, 'c) t
```

Build a one-dimensional Bigarray initialized from the given array.

```kotlin
val unsafe_get: ('a, 'b, 'c) t -> int -> 'a
```

Like `Bigarray.array1`. `get[28.5]`, but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds.

```kotlin
val unsafe_set: ('a, 'b, 'c) t -> int -> 'a -> unit
```

Like `Bigarray.array1`. `set[28.5]`, but bounds checking is not always performed. Use with caution and only when the program logic guarantees that the access is within bounds.

end
### `val current : int ref`

Position (in `Sys.argv[29.60]`) of the argument being processed. You can change this value, e.g. to force `Arg.parse[29.1]` to skip some arguments. `Arg.parse[29.1]` uses the initial value of `Arg.current[29.1]` as the index of argument 0 (the program name) and starts parsing arguments at the next element.

### `val read_arg : string -> string array`

`Arg.read_arg` file reads newline-terminated command line arguments from file `file`.

**Since:** 4.05

### `val read_arg0 : string -> string array`

Identical to `Arg.read_arg[29.1]` but assumes null character terminated command line arguments.

**Since:** 4.05

### `val write_arg : string -> string array -> unit`

`Arg.write_arg` file `args` writes the arguments `args` newline-terminated into the file `file`. If any of the arguments in `args` contains a newline, use `Arg.write_arg0[29.1]` instead.

**Since:** 4.05

### `val write_arg0 : string -> string array -> unit`

Identical to `Arg.write_arg[29.1]` but uses the null character for terminator instead of newline.

**Since:** 4.05

## 29.2 Module Array : Array operations.

The labeled version of this module can be used as described in the `StdLabels[29.57]` module.

### `type 'a t = 'a array`

An alias for the type of arrays.

### `val length : 'a array -> int`

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

### `val get : 'a array -> int -> 'a`

`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`.

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

### `val set : 'a array -> int -> 'a -> unit`
One-dimensional arrays. The **Array1** structure provides operations similar to those of **Bigarray.Genarray**[28.5], but specialized to the case of one-dimensional arrays. (The **Bigarray Array2**[28.5] and **Bigarray Array3**[28.5] structures below provide operations specialized for two- and three-dimensional arrays.) Statically knowing the number of dimensions of the array allows faster operations, and more precise static type-checking.

## Two-dimensional arrays

module Array2 :
sig

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

The type of two-dimensional Bigarrays whose elements have OCaml type 'a, representation kind 'b, and memory layout 'c.

val create :
('a, 'b) Bigarray.kind ->
'c Bigarraylayout -> int -> int -> ('a, 'b, 'c) t

Array2.create kind layout dim1 dim2 returns a new Bigarray of two dimensions, whose size is dim1 in the first dimension and dim2 in the second dimension. kind and layout determine the array element kind and the array layout as described for Bigarray.Genarray.create[28.5].

val init :
('a, 'b) Bigarray.kind ->
'c Bigarraylayout ->
int -> int -> (int -> int -> 'a) -> ('a, 'b, 'c) t

Array2.init kind layout dim1 dim2 f returns a new Bigarray b of two dimensions, whose size is dim2 in the first dimension and dim2 in the second dimension. kind and layout determine the array element kind and the array layout as described for Bigarray.Genarray.create[28.5].

Each element Array2.get b i j of the array is initialized to the result of f i j.

In other words, Array2.init kind layout dim1 dim2 f tabulates the results of f applied to the indices of a new Bigarray whose layout is described by kind, layout, dim1 and dim2.

**Since:** 4.12

val dim1 : ('a, 'b, 'c) t -> int

Return the first dimension of the given two-dimensional Bigarray.

val dim2 : ('a, 'b, 'c) t -> int

Return the second dimension of the given two-dimensional Bigarray.
`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`.

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

**val make :** `int -> 'a -> 'a array`

`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the value of `x` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.

**val create_float :** `int -> float array`

`create_float n` returns a fresh float array of length `n`, with uninitialized data.

**Since:** 4.03

**val init :** `int -> (int -> 'a) -> 'a array`

`init n f` returns a fresh array 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 in order to the integers 0 to `n-1`.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_array_length`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.

**val make_matrix :** `int -> int -> 'a -> 'a array array`

`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element `(x,y)` of a matrix `m` is accessed with the notation `m.(x).(y)`.

**Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than `Sys.max_array_length[29.60]`. If the value of `e` is a floating-point number, then the maximum size is only `Sys.max_array_length / 2`.

**val init_matrix :** `int -> int -> (int -> int -> 'a) -> 'a array 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`. The element `(x,y)` of a matrix `m` is accessed with the notation `m.(x).(y)`.

**Since:** 5.2

**Raises** `Invalid_argument` if `dimx` or `dimy` is negative or greater than `Sys.max_array_length[29.60]`. If the return type of `f` is `float`, then the maximum size is only `Sys.max_array_length / 2`.

**val append :** `'a array -> 'a array -> 'a array`
```ksharp
val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind
```

Return the kind of the given Bigarray.

```ksharp
val layout : ('a, 'b, 'c) t -> 'c Bigarraylayout
```

Return the layout of the given Bigarray.

```ksharp
val change_layout : ('a, 'b, 'c) t ->
'd Bigarraylayout -> ('a, 'b, 'd) t
```

Array2.change_layout a layout returns a Bigarray with the specified layout, sharing the data with a (and hence having the same dimensions as a). No copying of elements is involved: the new array and the original array share the same storage space. The dimensions are reversed, such that get v [| a; b |] in C layout becomes get v [| b+1; a+1 |] in Fortran layout.

Since: 4.06

```ksharp
val size_in_bytes : ('a, 'b, 'c) t -> int
```

size_in_bytes a is the number of elements in a multiplied by a's
Bigarray.kind_size_in_bytes[28.5].

Since: 4.03

```ksharp
val get : ('a, 'b, 'c) t -> int -> int -> 'a
```

Array2.get a x y, also written a.{x,y}, returns the element of a at coordinates (x, y). x and y must be within the bounds of a, as described for Bigarray.Genarray.get[28.5]; otherwise, Invalid_argument is raised.

```ksharp
val set : ('a, 'b, 'c) t -> int -> int -> 'a -> unit
```

Array2.set a x y v, or alternatively a.{x,y} <- v, stores the value v at coordinates (x, y) in a. x and y must be within the bounds of a, as described for Bigarray.Genarray.set[28.5]; otherwise, Invalid_argument is raised.

```ksharp
val sub_left :
('a, 'b, Bigarray.c_layout) t ->
int -> int -> ('a, 'b, Bigarray.c_layout) t
```

Extract a two-dimensional sub-array of the given two-dimensional Bigarray by
restricting the first dimension. See Bigarray.Genarray.sub_left[28.5] for more details.
Array2.sub_left applies only to arrays with C layout.

```ksharp
val sub_right :
('a, 'b, Bigarray.fortran_layout) t ->
int -> int -> ('a, 'b, Bigarray.fortran_layout) t
```

Extract a two-dimensional sub-array of the given two-dimensional Bigarray by
restricting the second dimension. See Bigarray.Genarray.sub_right[28.5] for more
details. Array2.sub_right applies only to arrays with Fortran layout.
append v1 v2 returns a fresh array containing the concatenation of the arrays v1 and v2.

**Raises** Invalid_argument if length v1 + length v2 > Sys.max_array_length.

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

Same as Array.append[29.2], but concatenates a list of arrays.

val sub : 'a array -> int -> int -> 'a array

sub a pos len returns a fresh array of length len, containing the elements number pos to
pos + len - 1 of array 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 : 'a array -> 'a array

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

val fill : 'a array -> int -> int -> 'a -> unit

fill a pos len x modifies the array 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 : 'a array -> int -> 'a array -> int -> int -> unit

blit src src_pos dst dst_pos len copies len elements from array src, starting at element number src_pos, to array dst, starting at element number dst_pos. It works correctly even if src and dst are the same array, 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 : 'a array -> 'a list

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

val of_list : 'a list -> 'a array

of_list l returns a fresh array containing the elements of l.

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

Comparison

val equal : ('a -> 'a -> bool) -> 'a array -> 'a array -> 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
```h
val slice_left :
    ('a, 'b, Bigarray.c_layout) t ->
    int -> ('a, 'b, Bigarray.c_layout) Bigarray Array1.t
```

Extract a row (one-dimensional slice) of the given two-dimensional Bigarray. The integer parameter is the index of the row to extract. See `Bigarray.Genarray.slice_left` [28.5] for more details. `Array2.slice_left` applies only to arrays with C layout.

```h
val slice_right :
    ('a, 'b, Bigarray.fortran_layout) t ->
    int -> ('a, 'b, Bigarray.fortran_layout) Bigarray Array1.t
```

Extract a column (one-dimensional slice) of the given two-dimensional Bigarray. The integer parameter is the index of the column to extract. See `Bigarray.Genarray.slice_right` [28.5] for more details. `Array2.slice_right` applies only to arrays with Fortran layout.

```h
val blit : ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
```

Copy the first Bigarray to the second Bigarray. See `Bigarray.Genarray.blit` [28.5] for more details.

```h
val fill : ('a, 'b, 'c) t -> 'a -> unit
```

Fill the given Bigarray with the given value. See `Bigarray.Genarray.fill` [28.5] for more details.

```h
val of_array :
    ('a, 'b) Bigarray.kind ->
    'c Bigarraylayout -> 'a array array -> ('a, 'b, 'c) t
```

Build a two-dimensional Bigarray initialized from the given array of arrays.

```h
val unsafe_get : ('a, 'b, 'c) t -> int -> int -> 'a
```

Like `Bigarray Array2.get` [28.5], but bounds checking is not always performed.

```h
val unsafe_set : ('a, 'b, 'c) t -> int -> int -> 'a -> unit
```

Like `Bigarray Array2.set` [28.5], but bounds checking is not always performed.

end

Two-dimensional arrays. The `Array2` structure provides operations similar to those of `Bigarray.Genarray` [28.5], but specialized to the case of two-dimensional arrays.
val compare : ('a -> 'a -> int) -> 'a array -> 'a array -> 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 : ('a -> unit) -> 'a array -> 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 -> 'a -> unit) -> 'a array -> unit

Same as Array.iter[29.2], but the function is applied to the index of the element as first argument, and the element itself as second argument.

val map : ('a -> 'b) -> 'a array -> 'b array

map 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_inplace : ('a -> 'a) -> 'a array -> 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 -> 'a -> 'b) -> 'a array -> 'b array

Same as Array.map[29.2], 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 -> 'a -> 'a) -> 'a array -> unit

Same as Array.map_inplace[29.2], 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 -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc

fold_left f init a computes f (... (f (f init a.(0)) a.(1)) ...) a.(n-1), where
n is the length of the array a.

val fold_left_map :

('acc -> 'a -> 'acc * 'b) -> 'acc -> 'a array -> 'acc * 'b array

fold_left_map is a combination of Array.fold_left[29.2] and Array.map[29.2] that
threads an accumulator through calls to f.

Since: 4.13
## Three-dimensional arrays

module Array3 :

sig

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

The type of three-dimensional Bigarrays whose elements have OCaml type 'a, representation kind 'b, and memory layout 'c.

val create :

('a, 'b) Bigarray.kind ->

'c Bigarraylayout -> int -> int -> int -> ('a, 'b, 'c) t

Array3.create kind layout dim1 dim2 dim3 returns a new Bigarray of three dimensions, whose size is dim1 in the first dimension, dim2 in the second dimension, and dim3 in the third. kind and layout determine the array element kind and the array layout as described for Bigarray.Genarray.create[28.5].

val init :

('a, 'b) Bigarray.kind ->

'c Bigarraylayout ->

int ->

int -> int -> (int -> int -> int -> 'a) -> ('a, 'b, 'c) t

Array3.init kind layout dim1 dim2 dim3 f returns a new Bigarray b of three dimensions, whose size is dim1 in the first dimension, dim2 in the second dimension, and dim3 in the third. kind and layout determine the array element kind and the array layout as described for Bigarray.Genarray.create[28.5].

Each element Array3.get b i j k of the array is initialized to the result of f i j k.

In other words, Array3.init kind layout dim1 dim2 dim3 f tabulates the results of f applied to the indices of a new Bigarray whose layout is described by kind, layout, dim1, dim2 and dim3.

Since: 4.12

val dim1 : ('a, 'b, 'c) t -> int

Return the first dimension of the given three-dimensional Bigarray.

val dim2 : ('a, 'b, 'c) t -> int

Return the second dimension of the given three-dimensional Bigarray.

val dim3 : ('a, 'b, 'c) t -> int

Return the third dimension of the given three-dimensional Bigarray.

val kind : ('a, 'b, 'c) t -> ('a, 'b) Bigarray.kind

Return the kind of the given Bigarray.
val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> '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 array a.

Iterators on two arrays

val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit
iter2 f a b applies function f to all the elements of a and b.

Since: 4.03 (4.05 in ArrayLabels)

Raises Invalid_argument if the arrays are not the same size.

val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
map2 f a b applies function f to all the elements of a and b, and builds an array with the
results returned by f: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b -
1)|].

Since: 4.03 (4.05 in ArrayLabels)

Raises Invalid_argument if the arrays are not the same size.

Array scanning

val for_all : ('a -> bool) -> 'a array -> bool
for_all f [|a1; ...; an|] checks if all elements of the array satisfy the predicate f. That
is, it returns (f a1) && (f a2) && ... && (f an).

Since: 4.03

val exists : ('a -> bool) -> 'a array -> bool
exists f [|a1; ...; an|] checks if at least one element of the array satisfies the predicate
f. That is, it returns (f a1) || (f a2) || ... || (f an).

Since: 4.03

val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as Array.for_all[29.2], but for a two-argument predicate.

Since: 4.11

Raises Invalid_argument if the two arrays have different lengths.

val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as Array.exists[29.2], but for a two-argument predicate.

Since: 4.11

Raises Invalid_argument if the two arrays have different lengths.
```h
val layout : ('a, 'b, 'c) t -> 'c Bigarraylayout
```

Return the layout of the given Bigarray.

```h
val change_layout : ('a, 'b, 'c) t ->
'd Bigarraylayout -> ('a, 'b, 'd) t
```

`Array3.change_layout` returns a Bigarray with the specified `layout`, sharing the data with `a` (and hence having the same dimensions as `a`). No copying of elements is involved: the new array and the original array share the same storage space. The dimensions are reversed, such that `get v [| a; b; c |]` in C layout becomes `get v [| c+1; b+1; a+1 |]` in Fortran layout.

**Since:** 4.06

```h
val size_in_bytes : ('a, 'b, 'c) t -> int
```

`size_in_bytes` is the number of elements in `a` multiplied by `a`'s `Bigarray.kind_size_in_bytes`[28.5].

**Since:** 4.03

```h
val get : ('a, 'b, 'c) t -> int -> int -> int -> 'a
```

`Array3.get` a x y z, also written `a.{x,y,z}`, returns the element of `a` at coordinates (x, y, z). `x`, `y` and `z` must be within the bounds of `a`, as described for `Bigarray.Genarray.get`[28.5]; otherwise, `Invalid_argument` is raised.

```h
val set : ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
```

`Array3.set` a x y v, or alternatively `a.{x,y,z} <- v`, stores the value `v` at coordinates (x, y, z) in `a`. `x`, `y` and `z` must be within the bounds of `a`, as described for `Bigarray.Genarray.set`[28.5]; otherwise, `Invalid_argument` is raised.

```h
val sub_left :
('a, 'b, Bigarray.c_layout) t ->
int -> int -> ('a, 'b, Bigarray.c_layout) t
```

Extract a three-dimensional sub-array of the given three-dimensional Bigarray by restricting the first dimension. See `Bigarray.Genarray.sub_left`[28.5] for more details. `Array3.sub_left` applies only to arrays with C layout.

```h
val sub_right :
('a, 'b, Bigarray.fortran_layout) t ->
int -> int -> ('a, 'b, Bigarray.fortran_layout) t
```

Extract a three-dimensional sub-array of the given three-dimensional Bigarray by restricting the second dimension. See `Bigarray.Genarray.sub_right`[28.5] for more details. `Array3.sub_right` applies only to arrays with Fortran layout.
val mem : 'a -> 'a array -> bool

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

Since: 4.03

val memq : 'a -> 'a array -> bool

Same as Array.mem[29.2], but uses physical equality instead of structural equality to compare
array elements.

Since: 4.03

val find_opt : ('a -> bool) -> 'a array -> 'a option

find_opt f a returns the first element of the array a that satisfies the predicate f, or None if
there is no value that satisfies f in the array a.

Since: 4.13

val find_index : ('a -> bool) -> 'a array -> 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 : ('a -> 'b option) -> 'a array -> 'b option

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

Since: 4.13

val find_mapi : (int -> 'a -> 'b option) -> 'a array -> '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

Arrays of pairs

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

split [|(a1,b1); ...; (an,bn)|] is ([|a1; ...; an|], [|b1; ...; bn|]).

Since: 4.13

val combine : 'a array -> 'b array -> ('a * 'b) array

combine [|a1; ...; an|] [|b1; ...; bn|] is [|(a1,b1); ...; (an,bn)|]. Raise Invalid_argument if the two arrays have different lengths.

Since: 4.13
```kotlin
val slice_left_1 :
    ('a', 'b', Bigarray.c_layout) t ->
    int -> int -> ('a', 'b', Bigarray.c_layout) Bigarray Array1.t
```

Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the first two coordinates. The integer parameters are the coordinates of the slice to extract. See `Bigarray.Genarray.slice_left[28.5]` for more details. `Array3.slice_left_1` applies only to arrays with C layout.

```kotlin
val slice_right_1 :
    ('a', 'b', Bigarray.fortran_layout) t ->
    int -> int -> ('a', 'b', Bigarray.fortran_layout) Bigarray Array1.t
```

Extract a one-dimensional slice of the given three-dimensional Bigarray by fixing the last two coordinates. The integer parameters are the coordinates of the slice to extract. See `Bigarray.Genarray.slice_right[28.5]` for more details. `Array3.slice_right_1` applies only to arrays with Fortran layout.

```kotlin
val slice_left_2 :
    ('a', 'b', Bigarray.c_layout) t ->
    int -> ('a', 'b', Bigarray.c_layout) Bigarray Array2.t
```

Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the first coordinate. The integer parameter is the first coordinate of the slice to extract. See `Bigarray.Genarray.slice_left[28.5]` for more details. `Array3.slice_left_2` applies only to arrays with C layout.

```kotlin
val slice_right_2 :
    ('a', 'b', Bigarray.fortran_layout) t ->
    int -> ('a', 'b', Bigarray.fortran_layout) Bigarray Array2.t
```

Extract a two-dimensional slice of the given three-dimensional Bigarray by fixing the last coordinate. The integer parameter is the coordinate of the slice to extract. See `Bigarray.Genarray.slice_right[28.5]` for more details. `Array3.slice_right_2` applies only to arrays with Fortran layout.

```kotlin
val blit : ('a', 'b', 'c') t -> ('a', 'b', 'c') t -> unit
```

Copy the first Bigarray to the second Bigarray. See `Bigarray.Genarray.blit[28.5]` for more details.

```kotlin
val fill : ('a', 'b', 'c') t -> 'a' -> unit
```

Fill the given Bigarray with the given value. See `Bigarray.Genarray.fill[28.5]` for more details.

```kotlin
val of_array :
    ('a', 'b') Bigarray.kind ->
    'c' Bigarraylayout -> 'a' array array array -> ('a', 'b', 'c') t
```
Sorting and shuffling

val sort : ('a -> 'a -> int) -> 'a array -> unit

Sort an array 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 array 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 : ('a -> 'a -> int) -> 'a array -> unit

Same as `Array.sort[29.2]`, 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 array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of `Array.sort[29.2]`.

val fast_sort : ('a -> 'a -> int) -> 'a array -> unit

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

val shuffle : rand:(int -> int) -> 'a array -> unit

shuffle `rand` a randomly permutes `a`'s element 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**
Build a three-dimensional Bigarray initialized from the given array of arrays of arrays.

```h
val unsafe_get: ('a, 'b, 'c) t -> int -> int -> int -> 'a
```

Like `Bigarray Array3`.get[28.5], but bounds checking is not always performed.

```h
val unsafe_set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
```

Like `Bigarray Array3`.set[28.5], but bounds checking is not always performed.

end

Three-dimensional arrays. The `Array3` structure provides operations similar to those of `Bigarray`.Genarray[28.5], but specialized to the case of three-dimensional arrays.

## Coercions between generic Bigarrays and fixed-dimension Bigarrays

```h
val genarray_of_array0: ('a, 'b, 'c) Array0.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given zero-dimensional Bigarray.
```
**Since:** 4.05

```h
val genarray_of_array1: ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given one-dimensional Bigarray.
```

```h
val genarray_of_array2: ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given two-dimensional Bigarray.
```

```h
val genarray_of_array3: ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t
Return the generic Bigarray corresponding to the given three-dimensional Bigarray.
```

```h
val array0_of_genarray: ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array0.t
Return the zero-dimensional Bigarray corresponding to the given generic Bigarray.
```

**Since:** 4.05

**Raises** Invalid_argument if the generic Bigarray does not have exactly zero dimension.

```h
val array1_of_genarray: ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array1.t
Return the one-dimensional Bigarray corresponding to the given generic Bigarray.
```

**Raises** Invalid_argument if the generic Bigarray does not have exactly one dimension.

```h
val array2_of_genarray: ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array2.t
Return the two-dimensional Bigarray corresponding to the given generic Bigarray.
```

**Raises** Invalid_argument if the generic Bigarray does not have exactly two dimensions.

```h
val array3_of_genarray: ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array3.t
Return the three-dimensional Bigarray corresponding to the given generic Bigarray.
```

**Raises** Invalid_argument if the generic Bigarray does not have exactly three dimensions.
## Arrays and Sequences

`val to_seq : 'a array -> 'a Seq.t`

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

**Since:** 4.07

`val to_seqi : 'a array -> (int * 'a) Seq.t`

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

**Since:** 4.07

`val of_seq : 'a Seq.t -> 'a array`

Create an array from the generator

**Since:** 4.07

## Arrays and concurrency safety

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

## Atomicity

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

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

After executing this code, each field of the 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.
## Re-shaping Bigarrays

```k language="k language="k language="k language="k
val reshape : 
  ('a, 'b, 'c) Genarray.t ->
  int array -> ('a, 'b, 'c) Genarray.t

  reshape b [|d1;...;dN|] converts the Bigarray b to a N-dimensional array of dimensions
d1...dN. The returned array and the original array b share their data and have the same
layout. For instance, assuming that b is a one-dimensional array of dimension 12, reshape b
[|3;4|] returns a two-dimensional array b' of dimensions 3 and 4. If b has C layout, the
element (x,y) of b' corresponds to the element x * 3 + y of b. If b has Fortran layout, the
element (x,y) of b' corresponds to the element x + (y - 1) * 4 of b. The returned
Bigarray must have exactly the same number of elements as the original Bigarray b. That is,
the product of the dimensions of b must be equal to i1 * ... * iN. Otherwise,
Invalid_argument is raised.
```

```k language="k language="k language="k language="k
val reshape_0 : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array0.t
```
Specialized version of `Bigarray reshape[28.5]` for reshaping to zero-dimensional arrays.

**Since: 4.05**

```k language="k language="k language="k language="k
val reshape_1 : ('a, 'b, 'c) Genarray.t -> int -> ('a, 'b, 'c) Array1.t
```
Specialized version of `Bigarray reshape[28.5]` for reshaping to one-dimensional arrays.

```k language="k language="k language="k language="k
val reshape_2 : 
  ('a, 'b, 'c) Genarray.t ->
  int -> int -> ('a, 'b, 'c) Array2.t
```
Specialized version of `Bigarray. reshape[28.5]` for reshaping to two-dimensional arrays.

```k language="k language="k language="k language="k
val reshape_3 : 
  ('a, 'b, 'c) Genarray.t ->
  int -> int -> int -> ('a, 'b, 'c) Array3.t
```
Specialized version of `Bigarray. reshape[28.5]` for reshaping to three-dimensional arrays.

## Bigarrays and concurrency safety

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

## Atomicity

Every bigarray operation that accesses more than one array element is not atomic. This includes slicing, bliting, and filling bigarrays.

For example, consider the following program:

```k language="k
open Bigarray
```
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 for float arrays).

## Float arrays

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 = Array.make size 0.
let max_floats = Array.make size Float.max_float
let res = Array.copy zeros
let d1 = Domain spawn (fun () -> Array.blit zeros 0 res 0 size)
let d2 = Domain spawn (fun () -> Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
```

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

## 29.3 Module ArrayLabels : Array operations.

The labeled version of this module can be used as described in the StdLabels[29.57] module.

```javascript
type 'a t = 'a array
```

An alias for the type of arrays.

```javascript
val length : 'a array -> int
```

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

```javascript
val get : 'a array -> int -> 'a
```

`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`.

**Raises** Invalid_argument if `n` is outside the range 0 to (`length a` - 1).
```pascal
let size = 100_000_000
let a = Array1.init Int C_layout size (fun _ -> 1)
let update f a () =
  for i = 0 to size - 1 do a.{i} <- f a.{i} done
let d1 = Domain spawn (update (fun x -> x + 1) a)
let d2 = Domain spawn (update (fun x -> 2 * x + 1) a)
let () = Domain.join d1; Domain.join d2
```

After executing this code, each field of the bigarray `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[28.36]`).

## Data races

If two domains only access disjoint parts of the bigarray, 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 bigarray 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 bigarray 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.

## Tearing

Bigarrays have a distinct caveat in the presence of data races: concurrent bigarray operations might produce surprising values due to tearing. More precisely, the interleaving of partial writes and reads might create values that would not exist with a sequential execution. For instance, at the end of

```pascal
let res = Array1.init Complex64 c_layout size (fun _ -> Complex.zero)
let d1 = Domain spawn (fun () -> Array1.fill res Complex.one)
let d2 = Domain spawn (fun () -> Array1.fill res Complex.i)
let () = Domain.join d1; Domain.join d2
```

the `res` bigarray might contain values that are neither `Complex.i` nor `Complex.one` (for instance 1 + i).

## 28.6 Module Bool : Boolean values.

Since: 4.08

### Booleans

```pascal
type t = bool =
  | false
```
val set : 'a array -> int -> 'a -> unit

set a n x modifies array a in place, replacing element number n with x. You can also write
a.(n) <- x instead of set a n x.

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

val make : int -> 'a -> 'a array

make n x returns a fresh array of length n, initialized with x. All the elements of this new
array are initially physically equal to x (in the sense of the == predicate). Consequently, if x
is mutable, it is shared among all elements of the array, and modifying x through one of the
array entries will modify all other entries at the same time.

Raises Invalid_argument if n < 0 or n > Sys.max_array_length. If the value of x is a
floating-point number, then the maximum size is only Sys.max_array_length / 2.

val create_float : int -> float array

create_float n returns a fresh float array of length n, with uninitialized data.

Since: 4.03

val init : int -> f:(int -> 'a) -> 'a array

init n ~f returns a fresh array 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 in order to the integers 0
to n-1.

Raises Invalid_argument if n < 0 or n > Sys.max_array_length. If the return type of f
is float, then the maximum size is only Sys.max_array_length / 2.

val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array

make_matrix ~dimx ~dimy e returns a two-dimensional array (an array of arrays) with first
dimension dimx and second dimension dimy. All the elements of this new matrix are initially
physically equal to e. The element (x,y) of a matrix m is accessed with the notation
m.(x).(y).

Raises Invalid_argument if dimx or dimy is negative or greater than
Sys.max_array_length[29.60]. If the value of e is a floating-point number, then the
maximum size is only Sys.max_array_length / 2.

val init_matrix :

dimx:int -> dimy:int -> f:(int -> int -> 'a) -> 'a array 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. The element (x,y) of a matrix m is accessed with the notation m.(x).(y).

Since: 5.2

Raises Invalid_argument if dimx or dimy is negative or greater than
Sys.max_array_length[29.60]. If the return type of f is float, then the maximum size is
only Sys.max_array_length / 2.
| true

The type of booleans (truth values).

The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types.

val not : bool -> bool

not b is the boolean negation of b.

val (&&) : bool -> bool -> bool

e0 && e1 is the lazy boolean conjunction of expressions e0 and e1. If e0 evaluates to `false`, e1 is not evaluated. Right-associative operator at precedence level 3/11.

val (||) : bool -> bool -> bool

e0 || e1 is the lazy boolean disjunction of expressions e0 and e1. If e0 evaluates to `true`, e1 is not evaluated. Right-associative operator at precedence level 2/11.

## Predicates and comparisons

val equal : bool -> bool -> bool

equal b0 b1 is true if and only if b0 and b1 are both true or both false.

val compare : bool -> bool -> int

compare b0 b1 is a total order on boolean values. false is smaller than true.

## Converting

val to_int : bool -> int

to_int b is 0 if b is false and 1 if b is true.

val to_float : bool -> float

to_float b is 0. if b is false and 1. if b is true.

val to_string : bool -> string

to_string b is "true" if b is true and "false" if b is false.

val seeded_hash : int -> bool -> int

A seeded hash function for booleans, 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 : bool -> int
val append : 'a array -> 'a array -> 'a array

append v1 v2 returns a fresh array containing the concatenation of the arrays v1 and v2.

Raises Invalid_argument if length v1 + length v2 > Sys.max_array_length.

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

Same as ArrayLabels.append[29.3], but concatenates a list of arrays.

val sub : 'a array -> pos:int -> len:int -> 'a array

sub a ~pos ~len returns a fresh array of length len, containing the elements number pos to
pos + len - 1 of array 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 : 'a array -> 'a array

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

val fill : 'a array -> pos:int -> len:int -> 'a -> unit

fill a ~pos ~len x modifies the array 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:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit

blit ~src ~src_pos ~dst ~dst_pos ~len copies len elements from array src, starting at element number src_pos, to array dst, starting at element number dst_pos. It works correctly even if src and dst are the same array, 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 : 'a array -> 'a list

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

val of_list : 'a list -> 'a array

of_list l returns a fresh array containing the elements of l.

Raises Invalid_argument if the length of l is greater than Sys.max_array_length.

Comparison

val equal : eq:('a -> 'a -> bool) -> 'a array -> 'a array -> 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
An unseeded hash function for booleans, 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.7 Module Buffer : Extensible buffers.

This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example:

```python
let concat_strings ss =
    let b = Buffer.create 16 in
    List.iter (Buffer.add_string b) ss;
    Buffer contents b
```

**Alert unsynchronized_access.** Unsynchronized accesses to buffers are a programming error.

### Unsynchronized accesses

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

### type t

The abstract type of buffers.

#### val create : int -> t

`create` n returns a fresh buffer, initially empty. The n parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than n characters are stored in the buffer, but shrinks back to n characters when `reset` is called. For best performance, n should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take n = 16 for instance. If n is not between 1 and Sys.max_string_length [28.55], it will be clipped to that interval.

#### val contents : t -> string

Return a copy of the current contents of the buffer. The buffer itself is unchanged.

#### val to_bytes : t -> bytes

Return a copy of the current contents of the buffer. The buffer itself is unchanged.

**Since: 4.02**

#### val sub : t -> int -> int -> string
val compare : cmp:('a -> 'a -> int) -> 'a array -> 'a array -> 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 : f:('a -> unit) -> 'a array -> 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 : f:(int -> 'a -> unit) -> 'a array -> unit

Same as ArrayLabels.iter[29.3], but the function is applied to the index of the element as first argument, and the element itself as second argument.

val map : f:('a -> 'b) -> 'a array -> 'b array

map ~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_inplace : f:('a -> 'a) -> 'a array -> unit

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

Since: 5.1

val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array

Same as ArrayLabels.map[29.3], but the function is applied to the index of the element as first argument, and the element itself as second argument.

val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit

Same as ArrayLabels.map_inplace[29.3], 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 : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc

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

val fold_left_map : f:('acc -> 'a -> 'acc * 'b) -> init:'acc -> 'a array -> 'acc * 'b array

fold_left_map is a combination of ArrayLabels.fold_left[29.3] and ArrayLabels.map[29.3] that threads an accumulator through calls to f.

Since: 4.13
`Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`.

**Raises** `Invalid_argument` if `off` and `len` do not designate a valid range of `b`.

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

`Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`.

**Since:** 3.11.2

**Raises** `Invalid_argument` if `srcoff` and `len` do not designate a valid range of `src`, or if `dstoff` and `len` do not designate a valid range of `dst`.

`val nth : t -> int -> char`

Get the n-th character of the buffer.

**Raises** `Invalid_argument` if `index` out of bounds

`val length : t -> int`

Return the number of characters currently contained in the buffer.

`val clear : t -> unit`

Empty the buffer.

`val reset : t -> unit`

Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by `Buffer.create[28.7]` `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer.

`val output_buffer : out_channel -> t -> unit`

`output_buffer` oc `b` writes the current contents of buffer `b` on the output channel `oc`.

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

`truncate b len` truncates the length of `b` to `len`. Note: the internal byte sequence is not shortened.

**Since:** 4.05

**Raises** `Invalid_argument` if `len < 0` or `len > length b`.

## Appending

Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond `Sys.max_string_length[28.55]`.

`val add_char : t -> char -> unit`

`add_char b c` appends the character `c` at the end of buffer `b`.
val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> 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 array a.

Iterators on two arrays

val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit
iter2 ~f a b applies function f to all the elements of a and b.

Since: 4.05

Raises Invalid_argument if the arrays are not the same size.

val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array
map2 ~f a b applies function f to all the elements of a and b, and builds an array with the
results returned by f: [| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b -
1)|].

Since: 4.05

Raises Invalid_argument if the arrays are not the same size.

Array scanning

val for_all : f:('a -> bool) -> 'a array -> bool
for_all ~f [|a1; ...; an|] checks if all elements of the array satisfy the predicate f.
That is, it returns (f a1) && (f a2) && ... && (f an).

Since: 4.03

val exists : f:('a -> bool) -> 'a array -> bool
exists ~f [|a1; ...; an|] checks if at least one element of the array satisfies the
predicate f. That is, it returns (f a1) || (f a2) || ... || (f an).

Since: 4.03

val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as ArrayLabels.for_all[29.3], but for a two-argument predicate.

Since: 4.11

Raises Invalid_argument if the two arrays have different lengths.

val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool
Same as ArrayLabels.exists[29.3], but for a two-argument predicate.

Since: 4.11

Raises Invalid_argument if the two arrays have different lengths.
val add_utf_8_uchar : t -> Uchar.t -> unit

add_utf_8_uchar b u appends the UTF-8[https://tools.ietf.org/html/rfc3629]
encoding of u at the end of buffer b.

Since: 4.06

val add_utf_16le_uchar : t -> Uchar.t -> unit

add_utf_16le_uchar b u appends the
UTF-16LE[https://tools.ietf.org/html/rfc2781] encoding of u at the end of buffer b.

Since: 4.06

val add_utf_16be_uchar : t -> Uchar.t -> unit

add_utf_16be_uchar b u appends the
UTF-16BE[https://tools.ietf.org/html/rfc2781] encoding of u at the end of buffer b.

Since: 4.06

val add_string : t -> string -> unit

add_string b s appends the string s at the end of buffer b.

val add_bytes : t -> bytes -> unit

add_bytes b s appends the byte sequence s at the end of buffer b.

Since: 4.02

val add_substring : t -> string -> int -> int -> unit

add_substring b s ofs len takes len characters from offset ofs in string s and appends them at the end of buffer b.

Raises Invalid_argument if ofs and len do not designate a valid range of s.

val add_subbytes : t -> bytes -> int -> int -> unit

add_subbytes b s ofs len takes len characters from offset ofs in byte sequence s and appends them at the end of buffer b.

Since: 4.02

Raises Invalid_argument if ofs and len do not designate a valid range of s.

val add_substitute : t -> (string -> string) -> string -> unit

add_substitute b f s appends the string pattern s at the end of buffer b with substitution.
The substitution process looks for variables into the pattern and substitutes each variable
name by its value, as obtained by applying the mapping f to the variable name. Inside the
string pattern, a variable name immediately follows a non-escaped $ character and is one of
the following:

* a non empty sequence of alphanumeric or _ characters,
val mem : 'a -> set:'a array -> bool

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

Since: 4.03

val memq : 'a -> set:'a array -> bool

Same as ArrayLabels.mem[29.3], but uses physical equality instead of structural equality to
compare array elements.

Since: 4.03

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

find_opt ~f a returns the first element of the array a that satisfies the predicate f, or None
if there is no value that satisfies f in the array a.

Since: 4.13

val find_index : f:('a -> bool) -> 'a array -> 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 : f:('a -> 'b option) -> 'a array -> 'b option

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

Since: 4.13

val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> '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

Arrays of pairs

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

split [|(a1,b1); ...; (an,bn)|] is ([|a1; ...; an|], [|b1; ...; bn|]).

Since: 4.13

val combine : 'a array -> 'b array -> ('a * 'b) array

combine [|a1; ...; an|] [|b1; ...; bn|] is [|(a1,b1); ...; (an,bn)|]. Raise Invalid_argument if the two arrays have different lengths.

Since: 4.13
* an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; it then stands for a plain `$`.

**Raises** `Not_found` if the closing character of a parenthesized variable cannot be found.

val add_buffer : t -> t -> unit

`add_buffer` `b1` `b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified.

val add_channel : t -> in_channel -> int -> unit

`add_channel` `b` `ic` `n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`.

**Raises**

* `End_of_file` if the channel contains fewer than `n` characters. In this case, the characters are still added to the buffer, so as to avoid loss of data.

* `Invalid_argument` if `len` < 0 or `len` > `Sys.max_string_length`.

## Buffers and Sequences

val to_seq : t -> char Seq.t

Iterate on the buffer, in increasing order.

The behavior is not specified if the buffer is modified during iteration.

**Since:** 4.07

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

Iterate on the buffer, in increasing order, yielding indices along `chars`.

The behavior is not specified if the buffer is modified during iteration.

**Since:** 4.07

val add_seq : t -> char Seq.t -> unit

Add `chars` to the buffer

**Since:** 4.07

val of_seq : char Seq.t -> t

Create a buffer from the generator

**Since:** 4.07