(********************************************************************)
(*  OCaml code from the book ``Learn Programming with OCaml''       *)
(*  See https://usr.lmf.cnrs.fr/lpo/                                *)
(*                                                                  *)
(*  Sylvain Conchon and Jean-Christophe Filliâtre                   *)
(*  Copyright 2025 Université Paris-Saclay and CNRS                 *)
(*                                                                  *)
(*  Openly licensed via CC BY SA 4.0                                *)
(*  See https://creativecommons.org/licenses/by-sa/4.0/deed.en      *)
(********************************************************************)

(* Program 18 on page 168
   Resizeable Arrays *)

  type 'a t = {
    default: 'a;
    mutable size: int;
    mutable data: 'a array;
  }

  let length a = a.size

  let make n d = { default = d; size = n; data = Array.make n d }

  let get a i =
    if i < 0 || i >= a.size then invalid_arg "get";
    a.data.(i)

  let set a i v =
    if i < 0 || i >= a.size then invalid_arg "set";
    a.data.(i) <- v

  let resize a s =
    if s <= a.size then
      Array.fill a.data s (a.size - s) a.default
    else begin
      let n = Array.length a.data in
      if s > n then begin
        let n' = max (2 * n) s in
        let a' = Array.make n' a.default in
        Array.blit a.data 0 a' 0 a.size;
        a.data <- a'
      end
    end;
    a.size <- s

This document was generated using caml2html