-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexpandarray.ml
69 lines (60 loc) · 1.27 KB
/
expandarray.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
type 'a t = {
mutable expand : 'a array;
mutable len : int;
};;
let create n = {
expand = Array.make n (Obj.magic None); (* BREAKING THE LAW! *)
len = 0;
};;
let get a n =
if n >= a.len || n < 0 then (
raise (Invalid_argument "index out of bounds")
) else (
a.expand.(n)
)
;;
let set a n x =
if n >= a.len then (
if n >= Array.length a.expand then (
(* Need to expand the array *)
let rec find_new_len q = if q > n then q else find_new_len (q lsl 1 lor 1) in
let q = find_new_len (Array.length a.expand) in
let newarray = Array.make q (Obj.magic None) in
Array.blit a.expand 0 newarray 0 (Array.length a.expand);
a.expand <- newarray;
);
for i = a.len to n do
a.expand.(i) <- x;
done;
a.len <- n + 1;
) else (
a.expand.(n) <- x;
)
;;
let add a x =
set a a.len x
;;
let length a = a.len;;
let to_array a = Array.sub a.expand 0 a.len;;
let of_array a = {
expand = Array.copy a;
len = Array.length a;
};;
let iter f a = (
let rec reciter i = (
if i >= a.len then () else (
f a.expand.(i);
reciter (succ i)
)
) in
reciter 0
);;
let iteri f a = (
let rec reciter i = (
if i >= a.len then () else (
f i a.expand.(i);
reciter (succ i)
)
) in
reciter 0
);;