Skip to content

Instantly share code, notes, and snippets.

@mheiber
Created November 7, 2022 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mheiber/059de3a58c584000bbced7e057ab292a to your computer and use it in GitHub Desktop.
Save mheiber/059de3a58c584000bbced7e057ab292a to your computer and use it in GitHub Desktop.
module Compact_array = struct
type 'a t = { len: unit -> int
 ; get: int -> 'a
 ; set: int -> 'a -> unit
 }
let of_string s =
 { len = (fun () -> String.length s)
 ; get = (fun i -> String.get s i)
 ; set = (fun i x -> String.set s i x)
 }
let of_array a =
 { len = (fun () -> Array.length a)
 ; get = (fun i -> Array.get a i)
 ; set = (fun i x -> Array.set a i x)
 }
let length t = t.len ()
 let get t i = t.get i
 let set t i x = t.set i x
end
module Compact_array = struct
 type ('in_, 'out) ops =
 { len : 'in_ -> int
 ; get : 'in_ -> int -> 'out
 }
type ('in_, 'out) t = 'in_ * ('in_, 'out) ops
let bytes_ops = { len = Bytes.length; get = Bytes.get }
 let array_ops = { len = Array.length; get = Array.get }
 let of_bytes s = s, bytes_ops
 let of_array a = a, array_ops
 let length (t, ops) = ops.len t
 let get (t, ops) i = ops.get t i
end
module Compact_array = struct
 type 'a t =
 | Array : 'a array -> 'a t
 | Bytes : bytes -> char t
let of_bytes x = Bytes x
 let of_array x = Array x
let length (type el) (t : el t) =
 match t with
 | Array a -> Array.length a
 | Bytes s -> Bytes.length s
let get (type el) (t : el t) i : el =
 match t with
 | Array a -> Array.get a i
 | Bytes s -> Bytes.get s i
let set (type el) (t : el t) i (v : el) =
 match t with
 | Array a -> Array.set a i v
 | Bytes s -> Bytes.set s i v
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment