comparison 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
comparison
equal deleted inserted replaced
-1:000000000000 0:bfdcc3820b32
1 (* lib/growvect.ml *)
2 (* Copyright (c) 2017 J. M. Spivey *)
3
4 type 'a t =
5 { mutable size: int;
6 mutable elements: 'a array }
7
8 let create n =
9 { size = 0; elements = Array.make n (Obj.magic ()) }
10
11 let make n v =
12 { size = n; elements = Array.make n v }
13
14 let clear v =
15 v.size <- 0
16
17 let size v = v.size
18
19 let get v i =
20 if i >= v.size then raise (Invalid_argument "index out of bounds");
21 Array.get v.elements i
22
23 let set v i x =
24 if i >= v.size then raise (Invalid_argument "index out of bounds");
25 Array.set v.elements i x
26
27 let append v x =
28 let n = Array.length v.elements in
29 if v.size >= n then begin
30 let newv = Array.make (2*n) (Obj.magic ()) in
31 Array.blit v.elements 0 newv 0 n;
32 v.elements <- newv
33 end;
34 Array.set v.elements v.size x;
35 v.size <- v.size+1
36
37 let iter f v =
38 for i = 0 to v.size-1 do f v.elements.(i) done
39
40 let to_list v =
41 let rec loop n xs =
42 if n = 0 then xs else loop (n-1) (v.elements.(n-1)::xs) in
43 loop v.size []