Float.ArrayLabels(3)
πΈ NAME πΈ
okay so bestie, this is Float.ArrayLabels(3) from the OCaml library, and it's literally the labeled-functions era of flat float arrays β main character energy only π
β¨
Float.ArrayLabels - Float arrays with packed representation (labeled functions).
π¦ Module π¦
Module Float.ArrayLabels
β¨ Documentation β¨
Module ArrayLabels : sig end
Float arrays with packed representation (labeled functions). π«Ά
type t = floatarray
The type of "flat" float arrays. π§
A floatarray is an array data structure that contains a fixed number of elements of type float. The elements of a floatarray are guaranteed to be stored contiguously in memory, without any boxing. no cap, that's the whole vibe π
Currently, the built-in type float array is optimized by default to also use an unboxed representation. However, this optimization may be disabled at configure-time when building the compiler. Furthermore, operations on floatarray are a bit more efficient than those on float array, which require an extra dynamic check. π₯
Array literals of type floatarray can be written using the same syntax as those of type float array as long as there is enough typing information in the environment so that the compiler can disambiguate between the two cases. See Section 12.25 'Type-directed disambiguation of array literals' of the manual for more details. π
Since 4.08
val length : t -> intβ Return the length (number of elements) of the givenfloatarray. πval get : t -> int -> floatβget a nreturns the element numbernoffloatarray a.
π¨ Raises Invalid_argument if n is outside the range 0 to (length a - 1).
val set : t -> int -> float -> unitβset a n xmodifiesfloatarray ain place, replacing element numbernwithx.
π¨ Raises Invalid_argument if n is outside the range 0 to (length a - 1).
val make : int -> float -> tβmake n xreturns a freshfloatarrayof lengthn, initialized withx.
π¨ Raises Invalid_argument if n < 0 or n > Sys.max_floatarray_length.
val create : int -> tβcreate nreturns a freshfloatarrayof lengthn, with uninitialized data.
π¨ Raises Invalid_argument if n < 0 or n > Sys.max_floatarray_length.
val init : int -> f:(int -> float) -> tβinit n ~freturns a freshfloatarrayof lengthn, with element numberiinitialized to the result off i. In other terms,init n ~ftabulates the results offapplied to the integers0ton-1.
π¨ Raises Invalid_argument if n < 0 or n > Sys.max_floatarray_length.
val make_matrix : dimx:int -> dimy:int -> float -> t arrayβmake_matrix ~dimx ~dimy ereturns a two-dimensional array (an array of arrays) with first dimensiondimxand second dimensiondimy, where all elements are initialized withe.
Since 5.2
π¨ Raises Invalid_argument if dimx or dimy is negative or greater than Sys.max_floatarray_length.
val init_matrix : dimx:int -> dimy:int -> f:(int -> int -> float) -> t 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.
Since 5.2
π¨ Raises Invalid_argument if dimx or dimy is negative or greater than Sys.max_floatarray_length.
val append : t -> t -> tβappend v1 v2returns a freshfloatarraycontaining the concatenation of the floatarraysv1andv2.
π¨ Raises Invalid_argument if length v1 + length v2 > Sys.max_floatarray_length.
val concat : t list -> tβ Same asFloat.ArrayLabels.append, but concatenates a list of floatarrays. π§΅val sub : t -> pos:int -> len:int -> tβsub a ~pos ~lenreturns a freshfloatarrayof lengthlen, containing the elements numberpostopos + len - 1offloatarray a.
π¨ Raises Invalid_argument if pos and len do not designate a valid subarray of a; that is, if pos < 0, or len < 0, or pos + len > length a.
val copy : t -> tβcopy areturns a copy ofa, that is, a freshfloatarraycontaining the same elements asa. πval fill : t -> pos:int -> len:int -> float -> unitβfill a ~pos ~len xmodifies thefloatarray ain place, storingxin elements numberpostopos + len - 1.
π¨ Raises Invalid_argument if pos and len do not designate a valid subarray of a.
val blit : src:t -> src_pos:int -> dst:t -> dst_pos:int -> len:int -> unitβblit ~src ~src_pos ~dst ~dst_pos ~lencopieslenelements fromfloatarray src, starting at element numbersrc_pos, tofloatarray dst, starting at element numberdst_pos. It works correctly even ifsrcanddstare the samefloatarray, and the source and destination chunks overlap. slay overlap safety π
π¨ Raises Invalid_argument if src_pos and len do not designate a valid subarray of src, or if dst_pos and len do not designate a valid subarray of dst.
val to_list : t -> float listβto_list areturns the list of all the elements ofa. πval of_list : float list -> tβof_list lreturns a freshfloatarraycontaining the elements ofl.
π¨ Raises Invalid_argument if the length of l is greater than Sys.max_floatarray_length.
π Comparison π
val equal : eq:(float -> float -> bool) -> t -> t -> boolβequal ~eq a bistrueif and only ifaandbhave the same lengthnand for alliin[ 0 ; n-1 ],eq a.(i) b.(i)istrue.
Since 5.4
val compare : cmp:(float -> float -> int) -> t -> t -> 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:(float -> unit) -> t -> 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 -> float -> unit) -> t -> unitβ Same asFloat.ArrayLabels.iter, but the function is applied with the index of the element as first argument, and the element itself as second argument. πval map : f:(float -> float) -> t -> tβmap ~f aapplies functionfto all the elements ofa, and builds afloatarraywith the results returned byf. β¨val map_inplace : f:(float -> float) -> t -> unitβmap_inplace ~f aapplies functionfto all elements ofa, and updates their values in place.
Since 5.1
val mapi : f:(int -> float -> float) -> t -> tβ Same asFloat.ArrayLabels.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 -> float -> float) -> t -> unitβ Same asFloat.ArrayLabels.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.1
val fold_left : f:('acc -> float -> 'acc) -> init:'acc -> t -> 'accβfold_left ~f ~init acomputesf (... (f (f init a.(0)) a.(1)) ...) a.(n-1), wherenis the length of thefloatarray a. π«Άval fold_right : f:(float -> 'acc -> 'acc) -> t -> init:'acc -> 'accβfold_right ~f a ~initcomputesf a.(0) (f a.(1) ( ... (f a.(n-1) init) ...)), wherenis the length of thefloatarray a.
π«Ά Iterators on two arrays π«Ά
val iter2 : f:(float -> float -> unit) -> t -> t -> unitβiter2 ~f a bapplies functionfto all the elements ofaandb.
π¨ Raises Invalid_argument if the floatarrays are not the same size.
val map2 : f:(float -> float -> float) -> t -> t -> tβmap2 ~f a bapplies functionfto all the elements ofaandb, and builds afloatarraywith the results returned byf:[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|].
π¨ Raises Invalid_argument if the floatarrays are not the same size.
π Array scanning π
val for_all : f:(float -> bool) -> t -> boolβfor_all ~f [|a1; ...; an|]checks if all elements of thefloatarraysatisfy the predicatef. That is, it returns(f a1) && (f a2) && ... && (f an). βval exists : f:(float -> bool) -> t -> boolβexists ~f [|a1; ...; an|]checks if at least one element of thefloatarraysatisfies the predicatef. That is, it returns(f a1) || (f a2) || ... || (f an). πval mem : float -> set:t -> boolβmem a ~setistrueif and only if there is an element ofsetthat is structurally equal toa, i.e. there is anxinsetsuch thatcompare a x = 0.val mem_ieee : float -> set:t -> boolβ Same asFloat.ArrayLabels.mem, but uses IEEE equality instead of structural equality. β‘
π΅οΈ Array searching π΅οΈ
val find_opt : f:(float -> bool) -> t -> float optionval find_index : f:(float -> bool) -> t -> 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 returns None if there is no such element.
Since 5.1
val find_map : f:(float -> 'a option) -> t -> 'a optionval find_mapi : f:(int -> float -> 'a option) -> t -> 'a 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
π² Sorting and shuffling π²
val sort : cmp:(float -> float -> int) -> t -> unitβ Sort afloatarrayin increasing order according to a comparison function. The comparison function must return0if 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,compareis a suitable comparison function. After callingsort, the array is sorted in place in increasing order.sortis guaranteed to run in constant heap space and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant stack space. π₯
Specification of the comparison function: Let a be the floatarray and cmp the comparison function. The following must be true for all x, y, z in a:
cmp x y > 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:(float -> float -> int) -> t -> unitβ Same asFloat.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 floatarray of length n/2, where n is the length of the floatarray. It is usually faster than the current implementation of Float.ArrayLabels.sort. π§
val fast_sort : cmp:(float -> float -> int) -> t -> unitβ Same asFloat.ArrayLabels.sortorFloat.ArrayLabels.stable_sort, whichever is faster on typical input. ποΈval shuffle : rand:(int -> int) -> t -> unitβshuffle ~rand arandomly permutesa's elements usingrandfor randomness. The distribution of permutations is uniform. π²β¨
okay so picking up right where we left off: rand has to be the kind of function where a call to rand n returns a uniformly distributed random number in the range [ 0 ; n-1 ]. You can totally use Random.int for this β just do not forget to Random.self_init the generator, bestie. π²
Since 5.2, iykyk. β¨
π¦ Float arrays and Sequences π¦
val to_seq : t -> float Seq.tβ iterate on the floatarray in increasing order. If you modify the floatarray while iterating, those changes will be reflected in the sequence. lowkey chaotic but that's the deal. πΈval to_seqi : t -> (int * float) Seq.tβ iterate on the floatarray in increasing order, yielding indices along with the elements. Same vibe: modifications during iteration show up in the sequence. πval of_seq : float Seq.t -> tβ create an array from the generator. slay. β¨val map_to_array : f:(float -> 'a) -> t -> 'a arrayβmap_to_array ~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) |]
val map_from_array : f:('a -> float) -> 'a array -> tβmap_from_array ~f aapplies functionfto all the elements ofa, and builds a floatarray with the results returned byf. iconic. π
π₯ Arrays and concurrency safety π₯
Care must be taken when concurrently accessing float arrays from multiple domains, bestie. Accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. so likeβ¦ not the vibe you want to find out the hard way. π
π Atomicity π
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. no cap.
For example, consider the following program:
let size = 100_000_000
let a = Float.ArrayLabels.make size 1.
let update a f () =
Float.ArrayLabels.iteri ~f:(fun i x -> Float.Array.set a i (f x)) a
let d1 = Domain.spawn (update a (fun x -> x +. 1.))
let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a is either 2., 3., 4. or 5.. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t). you gotta bring your own lock energy. π
π 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. cute.
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. periodt.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. fr fr, protect your elements.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. π
π§ Tearing π§
Float arrays have two supplementary caveats in the presence of data races. bestie, there's more.
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 = Float.Array.make size 0.
let max_floats = Float.Array.make size Float.max_float
let res = Float.Array.copy zeros
let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
the res float array might contain values that are neither 0. nor max_float. yeah. not it. π
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. so on 32-bit, tearing can show up anywhere. π«Ά
that's the whole vibe, bestie. source/version: OCamldoc Β· date: 2026-06-22 Β· page: Float.ArrayLabels(3) β mwah ππ
π¦ 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