Type rules:
ar : 'a array
, i : int
⇒ ar.(i) : 'a
ar : 'a array
, i : int
, e : 'a
⇒ ar.(i) <- e : unit
Runtime errors:
a.(i)
raises Invalid_argument "index out of bounds"
if i >= Array.length a
Strings are not mutable, but bytes
are:
let create_table n = Array.create n []
let hmod k t =
(Hashtbl.hash k) mod (Array.length t)
let add k v t =
let i = hmod k t in t.(i) <- (k,v)::t.(i)
let find k t = List.assoc k t.(hmod k t)
let mem k t = List.mem_assoc k t.(hmod k t)
let remove k t =
let i = hmod k t in
t.(i) <- List.remove_assoc k t.(i)
let update k v t =
let i = hmod k t in
t.(i) <- (k,v)::(List.remove_assoc k t.(i))
(OCaml Hashtbl
module has a more robust implementation)
let empty max = Array.make max false
let is_empty a = Array.for_all not a
let add i a = a.(i) <- true
let mem i a = a.(i)
let union s1 s2 = Array.map2 (||) s1 s2
let inter s1 s2 = Array.map2 (&&) s1 s2
let length s = Array.fold_left (fun a b -> if b then a+1 else a) 0 s
let fold_left f a s = snd (Array.fold_left
(fun (i,a) b -> (i+1, if b then (f a i) else a)) (0,a) s)
cs2041.org