StdLabels.Array(3)
πΈ NAME πΈ
okay bestie, welcome to StdLabels.Array(3) from the OCaml library β manual name folded in near the top like a tiny crown, exactly as requested. π The NAME section says StdLabels.Array and then, literally, no description. Thatβs it. No description. Weβre going in blind and honestly thatβs kind of iconic. π«Ά
π§ Module π§
Module Array
: (module ArrayLabels)
Main character energy: this module is ArrayLabels, and the page is about to walk us through every single val like a group chat recap. π
β¨ Documentation β¨
type 'a t = 'a array
An alias for the type of arrays. Same vibe, different name, no cap. π¦
val length : 'a array -> intβ returns the length, aka the number of elements, of the array you hand it. Short, sweet, slay. β¨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. Iconic shorthand, iykyk. 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. In-place update, very main character. 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. Shared mutable energy β be aware, bestie. π 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. Since4.03β vintage but still cute. πval 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). Since5.2β fresh off the release notes. 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. Two arrays walk into a functionβ¦ and become one. Periodt. 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. Group-chat merge, but make it 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. Clone era. π§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. Overlap? Handled. No cap. 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. Array to list pipeline, obsessed. π¦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 bistrueif and only ifaandbhave the same lengthnand for alliin[ 0 ; n-1 ],eq a.(i) b.(i)istrue. Since5.4β new-ish, and checking all the vibes. πval 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. Since5.4β shortlex is the moment. π₯
π₯ 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); (). Just doing laps through the array, bestie.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. Index + element = duo.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) |]. Glow-up every element. πval map_inplace : f:('a -> 'a) -> 'a array -> unitβmap_inplace ~f aapplies functionfto all elements ofa, and updates their values in place. Since5.1β same array, new you. π¦val 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. Index-aware mapping, very iykyk.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. Since5.1β in-place and indexed. πval 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. Accumulator threading, left to right. Slay.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. Since4.13β two icons in one function. πval 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. Right-to-left fold, still ate.
π¦ Iterators on two arrays π¦
val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unitβiter2 ~f a bapplies functionfto all the elements ofaandb. Since4.05. RaisesInvalid_argumentif 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)|]. Since4.05. RaisesInvalid_argumentif 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). Since4.03β all-clear energy. βval 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). Since4.03β one match is enough. β¨val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> boolβ Same asArrayLabels.for_all, but for a two-argument predicate. Since4.11. RaisesInvalid_argumentif 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. Since4.11. RaisesInvalid_argumentif the two arrays have different lengths.val mem : 'a -> set:'a array -> boolβmem a ~setistrueif and only ifais structurally equal to an element ofset(i.e. there is anxinsetsuch thatcompare a x = 0). Since4.03β structural equality checking. πval memq : 'a -> set:'a array -> boolβ Same asArrayLabels.mem, but uses physical equality instead of structural equality to compare array elements. Since4.03β physical equality, no cap. πval 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. Since4.13.val 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. Since5.1β index hunting era. π₯val 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. Since4.13.val 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 from0), and the element itself as second argument. Since5.1β indexed and searching. π¦
π Arrays of pairs π
val split : ('a * 'b) array -> 'a array * 'b arrayβsplit [|(a1,b1); ...; (an,bn)|]is([|a1; ...; an|], [|b1; ...; bn|]). Since4.13β pair separation, iconic. βοΈval 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. Since4.13β zipping them together. π
π Sorting and shuffling π
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
and thatβs exactly where this part cuts off β part 2 is pulling up with the rest. π
okay so sort is the whole vibe: it sorts 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 (there's a complete spec 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
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unitβ same asArrayLabels.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. π₯
val stable_sort_sub : cmp:('a -> 'a -> int) -> 'a array -> pos:int -> len:int -> unitβstable_sort_sub ~cmp a ~pos ~lensorts the subarray of the arrayadelimited by the start positionposand by the lengthlen. The data in this subarray is sorted in increasing order according to the comparison functioncmp. The data outside of this subarray is unaffected. The sorting algorithm is stable; it is the same as inArrayLabels.stable_sort.
Since 5.5
π¨ RaisesInvalid_argumentifposandlendo not designate a valid subarray ofa; that is, ifpos < 0, orlen < 0, orpos + len > length a.
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unitβ same asArrayLabels.sortorArrayLabels.stable_sort, whichever is faster on typical input. πval shuffle : rand:(int -> int) -> 'a array -> unitβshuffle ~rand arandomly permutesa's elements usingrandfor 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.07val 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.07val 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. no cap.
π 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. β¨
later bestie π this whole thing is from OCamldoc, dated 2026-06-22, and the page is StdLabels.Array(3) β periodt πβ¨
π¦ 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