Source

spotlib / lib / xhashtbl.ml

The default branch has multiple heads

Full commit
let replace_list tbl kvs = 
  List.iter (fun (k,v) ->
    Hashtbl.replace tbl k v) kvs

let of_list size kvs =
  let tbl = Hashtbl.create size in
  List.iter (fun (k,v) ->
    Hashtbl.replace tbl k v) kvs;
  tbl
  
let to_list tbl = Hashtbl.fold (fun k v st -> (k,v) :: st) tbl []

let find_opt tbl k = try Some (Hashtbl.find tbl k) with Not_found -> None

let find_default def tbl k = try Hashtbl.find tbl k with Not_found -> def

let find_or_add deff tbl k = 
  try Hashtbl.find tbl k with Not_found -> 
    let def = deff k in
    Hashtbl.replace tbl k def;
    def

let alter tbl k f =
  match f (find_opt tbl k) with
  | None -> Hashtbl.remove tbl k
  | Some v -> Hashtbl.replace tbl k v

let memoize tbl f k =
  try 
    Hashtbl.find tbl k 
  with
  | Not_found ->
      let v = f k in
      Hashtbl.replace tbl k v;
      v