Skip to content

Commit

Permalink
Add an immutable array structure
Browse files Browse the repository at this point in the history
  • Loading branch information
SquidDev committed Jan 8, 2024
1 parent d73e3a2 commit 2fbb4e4
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/illuaminate/iArray.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
include Array

let empty = [||]
let pp fmt = Fmt.Dump.array fmt

external of_array : 'a array -> 'a t = "%identity"

let of_list = Array.of_list

let of_rev_list = function
| [] -> empty
| hd :: _ as l ->
let len = List.length l in
let a = Array.make len hd in
let rec fill i = function
| [] -> a
| hd :: tl ->
unsafe_set a i hd;
fill (i - 1) tl
in
fill (len - 1) l

let set array idx value =
let array = Array.copy array in
array.(idx) <- value;
array
42 changes: 42 additions & 0 deletions src/illuaminate/iArray.mli
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
(** Immutable arrays.
This just provides a wrapper for the built-in {!Array} module, removing any functions which
modify the array. *)

type 'a t

(** The empty array. *)
val empty : 'a t

(** Pretty print an array. *)
val pp : 'a Fmt.t -> 'a t Fmt.t

(** {1 Creation} *)

(** Create an immutable array from an array.
The original array should not be modified after calling this function. *)
external of_array : 'a array -> 'a t = "%identity"

(** Create an immutable array from a list. *)
val of_list : 'a list -> 'a t

(** Create an immutable array from a reversed list. *)
val of_rev_list : 'a list -> 'a t

(** {1 Operations} *)

(** Return the length (number of elements) of the given array. *)
external length : 'a t -> int = "%array_length"

(** [get a n] returns the element number [n] of array [a]. *)
external get : 'a t -> int -> 'a = "%array_safe_get"

(** Set an element in this array, returning the new version of it. *)
val set : 'a t -> int -> 'a -> 'a t

(** Perform a left fold over this array. *)
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a

(** Iterate over each item in the array. *)
val iter : ('a -> unit) -> 'a t -> unit

0 comments on commit 2fbb4e4

Please sign in to comment.