ArrayLabels(3)
π NAME
ArrayLabels(3) is the OCaml library manual page for ArrayLabels β literally Array operations. That's the whole vibe, bestie. β¨
π§ Module
Module ArrayLabels β yes, that's the module name. Iconic. π
π Documentation
Module ArrayLabels
: sig end
Array operations. Yep, again. π
The labeled version of this module can be used as described in the StdLabels module. Slay.
type 'a t = 'a arrayβ an alias for the type of arrays. That's it. πval length : 'a array -> intβ returns the length (number of elements) of the given array. Lowkey essential. β¨val get : 'a array -> int -> 'aβget a nreturns the element numbernof arraya. The first element has number0. The last element has numberlength a - 1. You can also writea.(n)instead ofget a n.
β οΈ RaisesInvalid_argumentifnis outside the range0to(length a - 1).
val set : 'a array -> int -> 'a -> unitβset a n xmodifies arrayain place, replacing element numbernwithx. You can also writea.(n) <- xinstead ofset a n x.
β οΈ RaisesInvalid_argumentifnis outside the range0tolength a - 1.
val make : int -> 'a -> 'a arrayβmake n xreturns a fresh array of lengthn, initialized withx. All the elements of this new array are initially physically equal tox(in the sense of the==predicate). Consequently, ifxis mutable, it is shared among all elements of the array, and modifyingxthrough one of the array entries will modify all other entries at the same time.
β οΈ RaisesInvalid_argumentifn < 0orn > Sys.max_array_length. If the value ofxis a floating-point number, then the maximum size is onlySys.max_array_length / 2.
val create_float : int -> float arrayβcreate_float nreturns a fresh float array of lengthn, with uninitialized data. β¨ Since 4.03val init : int -> f:(int -> 'a) -> 'a arrayβinit n ~freturns a fresh array of lengthn, with element numberiinitialized to the result off i. In other terms,init n ~ftabulates the results offapplied in order to the integers0ton-1.
β οΈ RaisesInvalid_argumentifn < 0orn > Sys.max_array_length. If the return type offisfloat, then the maximum size is onlySys.max_array_length / 2.
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array arrayβmake_matrix ~dimx ~dimy ereturns a two-dimensional array (an array of arrays) with first dimensiondimxand second dimensiondimy. All the elements of this new matrix are initially physically equal toe. The element(x,y)of a matrixmis accessed with the notationm.(x).(y).
β οΈ RaisesInvalid_argumentifdimxordimyis negative or greater thanSys.max_array_length. If the value ofeis a floating-point number, then the maximum size is onlySys.max_array_length / 2.
val init_matrix : dimx:int -> dimy:int -> f:(int -> int -> 'a) -> 'a array arrayβinit_matrix ~dimx ~dimy ~freturns a two-dimensional array (an array of arrays) with first dimensiondimxand second dimensiondimy, where the element at index(x,y)is initialized withf x y. The element(x,y)of a matrixmis accessed with the notationm.(x).(y). β¨ Since 5.2
β οΈ RaisesInvalid_argumentifdimxordimyis negative or greater thanSys.max_array_length. If the return type offisfloat, then the maximum size is onlySys.max_array_length / 2.
val append : 'a array -> 'a array -> 'a arrayβappend v1 v2returns a fresh array containing the concatenation of the arraysv1andv2.
β οΈ RaisesInvalid_argumentiflength v1 + length v2 > Sys.max_array_length.
val concat : 'a array list -> 'a arrayβ Same asArrayLabels.append, but concatenates a list of arrays. π«Άval sub : 'a array -> pos:int -> len:int -> 'a arrayβsub a ~pos ~lenreturns a fresh array of lengthlen, containing the elements numberpostopos + len - 1of arraya.
β οΈ RaisesInvalid_argumentifposandlendo not designate a valid subarray ofa; that is, ifpos < 0, orlen < 0, orpos + len > length a.
val copy : 'a array -> 'a arrayβcopy areturns a copy ofa, that is, a fresh array containing the same elements asa. Fresh copy, no cap. πval fill : 'a array -> pos:int -> len:int -> 'a -> unitβfill a ~pos ~len xmodifies the arrayain place, storingxin elements numberpostopos + len - 1.
β οΈ RaisesInvalid_argumentifposandlendo not designate a valid subarray ofa.
val blit : src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unitβblit ~src ~src_pos ~dst ~dst_pos ~lencopieslenelements from arraysrc, starting at element numbersrc_pos, to arraydst, starting at element numberdst_pos. It works correctly even ifsrcanddstare the same array, and the source and destination chunks overlap.
β οΈ RaisesInvalid_argumentifsrc_posandlendo not designate a valid subarray ofsrc, or ifdst_posandlendo not designate a valid subarray ofdst.
val to_list : 'a array -> 'a listβto_list areturns the list of all the elements ofa. β¨val of_list : 'a list -> 'a arrayβof_list lreturns a fresh array containing the elements ofl.
β οΈ RaisesInvalid_argumentif the length oflis greater thanSys.max_array_length.
π₯ Comparison
val equal : eq:('a -> 'a -> bool) -> 'a array -> 'a array -> boolβequal eq a bis true if and only ifaandbhave the same lengthnand for alliin[ 0 ; n-1 ],eq a.(i) b.(i)is true. β¨ Since 5.4val compare : cmp:('a -> 'a -> int) -> 'a array -> 'a array -> intβcompare cmp a bcomparesaandbaccording to the shortlex order, that is, shorter arrays are smaller and equal-sized arrays are compared in lexicographic order usingcmpto compare elements. β¨ Since 5.4
π¦ Iterators
val iter : f:('a -> unit) -> 'a array -> unitβiter ~f aapplies functionfin turn to all the elements ofa. It is equivalent tof a.(0); f a.(1); ...; f a.(length a - 1); (). πval iteri : f:(int -> 'a -> unit) -> 'a array -> unitβ Same asArrayLabels.iter, 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 aapplies functionfto all the elements ofa, and builds an array with the results returned byf:[| f a.(0); f a.(1); ...; f a.(length a - 1) |]. Slay.val map_inplace : f:('a -> 'a) -> 'a array -> unitβmap_inplace ~f aapplies functionfto all elements ofa, and updates their values in place. β¨ Since 5.1val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b arrayβ Same asArrayLabels.map, 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 asArrayLabels.map_inplace, but the function is applied to the index of the element as first argument, and the element itself as second argument. β¨ Since 5.1val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'accβfold_left ~f ~init acomputesf (... (f (f init a.(0)) a.(1)) ...) a.(n-1), wherenis the length of the arraya.val fold_left_map : f:('acc -> 'a -> 'acc * 'b) -> init:'acc -> 'a array -> 'acc * 'b arrayβfold_left_mapis a combination ofArrayLabels.fold_leftandArrayLabels.mapthat threads an accumulator through calls tof. β¨ Since 4.13val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> init:'acc -> 'accβfold_right ~f a ~initcomputesf a.(0) (f a.(1) ( ... (f a.(n-1) init) ...)), wherenis the length of the arraya.
π Iterators on two arrays
val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unitβiter2 ~f a bapplies functionfto all the elements ofaandb. β¨ 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 bapplies functionfto all the elements ofaandb, and builds an array with the results returned byf:[| 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 predicatef. That is, it returns(f a1) && (f a2) && ... && (f an). β¨ Since 4.03val exists : f:('a -> bool) -> 'a array -> boolβexists ~f [|a1; ...; an|]checks if at least one element of the array satisfies the predicatef. That is, it returns(f a1) || (f a2) || ... || (f an). β¨ Since 4.03val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> boolβ Same asArrayLabels.for_all, 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 asArrayLabels.exists, 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 ~setis true if and only ifais structurally equal to an element ofset(i.e. there is anxinsetsuch thatcompare a x = 0). β¨ Since 4.03val memq : 'a -> set:'a array -> boolβ Same asArrayLabels.mem, but uses physical equality instead of structural equality to compare array elements. β¨ Since 4.03val find_opt : f:('a -> bool) -> 'a array -> 'a optionβfind_opt ~f areturns the first element of the arrayathat satisfies the predicatef, orNoneif there is no value that satisfiesfin the arraya. β¨ Since 4.13val find_index : f:('a -> bool) -> 'a array -> int optionβfind_index ~f areturnsSome i, whereiis the index of the first element of the arrayathat satisfiesf x, if there is such an element. It returnsNoneif there is no such element. β¨ Since 5.1val find_map : f:('a -> 'b option) -> 'a array -> 'b optionβfind_map ~f aappliesfto the elements ofain order, and returns the first result of the formSome v, orNoneif none exist. β¨ Since 4.13val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> 'b optionβ Same asfind_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.13val combine : 'a array -> 'b array -> ('a * 'b) arrayβcombine [|a1; ...; an|] [|b1; ...; bn|]is[|(a1,b1); ...; (an,bn)|]. RaiseInvalid_argumentif the two arrays have different lengths. β¨ Since 4.13
π Sorting and shuffling
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
Okay so, sorting an array in increasing order according to a comparison function. The comparison function has to 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 (full spec is literally right below, bestie). For example, compare 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 > 0if and only ifcmp y x < 0- if
cmp x y >= 0andcmp y z >= 0thencmp 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) >= 0ifi >= j
Now the stable one, because sometimes you want equal elements to keep their original order β iconic behaviour only:
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
Same as ArrayLabels.sort, 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.
Next up, sorting just a little subarray, because sometimes you don't need the whole thing:
val stable_sort_sub : cmp:('a -> 'a -> int) -> 'a array -> pos:int ->
len:int -> unit
stable_sort_sub ~cmp a ~pos ~len sorts the subarray of the array a delimited by the start position pos and by the length len. The data in this subarray is sorted in increasing order according to the comparison function cmp. The data outside of this subarray is unaffected. The sorting algorithm is stable; it is the same as in ArrayLabels.stable_sort.
Since 5.5
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.
And here's the "just pick the faster vibe" one:
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
Same as ArrayLabels.sort or ArrayLabels.stable_sort, whichever is faster on typical input.
Then we have shuffle, for when you need chaos but make it statistically correct:
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 can be used for this (do not forget to Random.self_init the generator).
Since 5.2
π 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 = ArrayLabels.make size 1
let d1 = Domain.spawn (fun () ->
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).
π¦ 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
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.
That's the whole tea, bestie π«Ά this page came from OCamldoc, dated 2026-06-22, and it's the ArrayLabels(3) manual page. Slay responsibly π
β¨
π¦ where this page comes from
- arch rolling: ocaml 5.5.0-1 Β· LGPL2.1 AND custom: QPL-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms