annotate lib/growvect.ml @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
rev   line source
mike@0 1 (* lib/growvect.ml *)
mike@0 2 (* Copyright (c) 2017 J. M. Spivey *)
mike@0 3
mike@0 4 type 'a t =
mike@0 5 { mutable size: int;
mike@0 6 mutable elements: 'a array }
mike@0 7
mike@0 8 let create n =
mike@0 9 { size = 0; elements = Array.make n (Obj.magic ()) }
mike@0 10
mike@0 11 let make n v =
mike@0 12 { size = n; elements = Array.make n v }
mike@0 13
mike@0 14 let clear v =
mike@0 15 v.size <- 0
mike@0 16
mike@0 17 let size v = v.size
mike@0 18
mike@0 19 let get v i =
mike@0 20 if i >= v.size then raise (Invalid_argument "index out of bounds");
mike@0 21 Array.get v.elements i
mike@0 22
mike@0 23 let set v i x =
mike@0 24 if i >= v.size then raise (Invalid_argument "index out of bounds");
mike@0 25 Array.set v.elements i x
mike@0 26
mike@0 27 let append v x =
mike@0 28 let n = Array.length v.elements in
mike@0 29 if v.size >= n then begin
mike@0 30 let newv = Array.make (2*n) (Obj.magic ()) in
mike@0 31 Array.blit v.elements 0 newv 0 n;
mike@0 32 v.elements <- newv
mike@0 33 end;
mike@0 34 Array.set v.elements v.size x;
mike@0 35 v.size <- v.size+1
mike@0 36
mike@0 37 let iter f v =
mike@0 38 for i = 0 to v.size-1 do f v.elements.(i) done
mike@0 39
mike@0 40 let to_list v =
mike@0 41 let rec loop n xs =
mike@0 42 if n = 0 then xs else loop (n-1) (v.elements.(n-1)::xs) in
mike@0 43 loop v.size []