File: hashtbl2.ml

package info (click to toggle)
caml2html 1.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, sid, stretch
  • size: 300 kB
  • sloc: ml: 1,996; makefile: 162
file content (90 lines) | stat: -rw-r--r-- 1,934 bytes parent folder | download | duplicates (2)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
type ('a, 'b) t = ('a, 'b list ref) Hashtbl.t

let create n = Hashtbl.create n
let clear = Hashtbl.clear

let add tbl key data =
  let r =
    try Hashtbl.find tbl key
    with Not_found ->
      let r = ref [] in
      Hashtbl.add tbl key r;
      r in
  r := data :: !r

let copy tbl =
  let tbl2 = Hashtbl.copy tbl in
  Hashtbl.iter (fun key r -> Hashtbl.replace tbl2 key (ref !r)) tbl;
  tbl2

let find tbl key =
  List.hd !(Hashtbl.find tbl key)

let find_all tbl key =
  !(Hashtbl.find tbl key)

let mem = Hashtbl.mem

let remove tbl key =
  try
    let r = Hashtbl.find tbl key in
    match !r with
	[data] -> Hashtbl.remove tbl key
      | hd :: tl -> r := tl
      | [] -> invalid_arg "remove"
  with Not_found -> ()

let remove_all = Hashtbl.remove

let replace tbl key data =
  try
    let r = Hashtbl.find tbl key in
    r := data :: (List.tl !r)
  with 
      Not_found -> Hashtbl.add tbl key (ref [data])

let replace_all tbl key l =
  try
    let r = Hashtbl.find tbl key in
    r := l
  with 
      Not_found -> Hashtbl.add tbl key (ref l)

let iter f tbl =
  Hashtbl.iter (fun key r -> f key (List.hd !r)) tbl

let iter_all f tbl =
  Hashtbl.iter (fun key r -> f key !r) tbl

let fold f tbl init =
  Hashtbl.fold (fun key r accu -> f key (List.hd !r) accu) tbl init

let fold_all f tbl init =
  Hashtbl.fold 
    (fun key r accu -> f key !r accu)
    tbl init

let list_keys tbl =
  fold (fun key _ accu -> key :: accu) tbl []

let list_values tbl =
  fold (fun _ data accu -> data :: accu) tbl []

let list_all_values tbl =
  fold_all (fun _ l accu -> l :: accu) tbl []

let list tbl =
  fold (fun key data accu -> (key, data) :: accu) tbl []

let list_all tbl =
  fold_all (fun key l accu -> (key, l) :: accu) tbl []

let of_list n l =
  let tbl = create n in
  List.iter (fun (key, data) -> add tbl key data) l;
  tbl

let of_keys n l =
  let tbl = create n in
  List.iter (fun key -> replace tbl key ()) l;
  tbl